c++ - 使用集合计算素数,C++

标签 c++ pointers iterator set

我正在尝试使用集合来计算素数,但是当我进行计算时,我的迭代器正在随机跳跃。

我正在尝试为 N=10 的值实现此方法。

Choose an integer n. This function will compute all prime numbers up to n. First insert all numbers from 1 to n into a set. Then erase all multiples of 2 (except 2); that is, 4, 6, 8, 10, 12, .... Erase all multiples of 3, that is, 6, 9, 12, 15, ... . Go up to sqrt(n) . The remaining numbers are all primes.

当我运行代码时,它会删除 1,然后 pos 跳转到 4?我不知道为什么会发生这种情况,而不是转到值 2,即集合中的第二个值?

此外,当我删除迭代器指向的值后会发生什么,迭代器指向什么,如果我将其推进到哪里?

这是代码:

set<int> sieveofEratosthenes(int n){ //n = 10

    set<int> a;
    set<int>::iterator pos = a.begin();

//generate set of values 1-10
    for (int i = 1; i <= n; i++) {
        a.insert(i);
        if(pos != a.end())
            pos++;
    }

    pos = a.begin();

    //remove prime numbers
    while (pos != a.end())
    {
        cout << "\nNew Iteration \n\n";

        for (int i = 1; i < sqrt(n); i++) {
            int val = *pos%i;

            cout << "Pos = " << *pos << "\n";
            cout << "I = " << i << "\n";
            cout << *pos << "/" << i << "=" << val << "\n\n";

            if (val == 0) {
                a.erase(i);
                }
            }
        pos++;
    }
    return a;
}

最佳答案

您的实现是不正确的,因为它试图将筛算法与尝试除数的简单算法结合起来,但没有成功。您不需要测试整除性来实现筛子 - 事实上,这是算法之美的主要贡献者!您甚至不需要乘法。

a.erase(1);
pos = a.begin();
while (pos != a.end()) {
    int current = *pos++;
    // "remove" is the number to remove.
    // Start it at twice the current number
    int remove = current + current;
    while (remove <= n) {
        a.erase(remove);
        // Add the current number to get the next item to remove
        remove += current;
    }
}

Demo.

关于c++ - 使用集合计算素数,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34422942/

相关文章:

python - 使用 python itertools 按相同的元组(时间戳)对元组列表进行分组

C++ random_shuffle 总是给出相同的结果

c++ - 需要协助 c++ 模板动态内存分配

c++ - 如何在 C++11 中使用 decltype 引用当前类?

c++ - 在 LuaSQL 代码上断言 C/C++

python - 如何一次读取文件 N 行?

pointers - 为什么使用不安全代码的二叉树在 Debug模式下内存访问错误,但在发布时却没有?

c++ - C++中的类查找结构数组

c - 在不取消引用 C 中的指针的情况下获取值

c++ - 如何迭代函数 vector 并在 C++ 中调用每个函数?