Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
给定范围内有多少素数?C++_C++_Algorithm_Primes - Fatal编程技术网

给定范围内有多少素数?C++

给定范围内有多少素数?C++,c++,algorithm,primes,C++,Algorithm,Primes,所以,我制作了这个小程序。它提供了所有正确的输出,但当上传到在线法官它扔我的时间限制超过。关于如何提高效率有什么想法吗 这是我的密码 int const MAX = 1000001; #include<iostream> #include<string> #include<cmath> using namespace std; int main() { int count = 0, array[MAX], a, b, pi = 0;

所以,我制作了这个小程序。它提供了所有正确的输出,但当上传到在线法官它扔我的时间限制超过。关于如何提高效率有什么想法吗

这是我的密码

int const MAX = 1000001;  
#include<iostream> 
#include<string>
#include<cmath>

using namespace std;

int main()
{
    int count = 0, array[MAX], a, b, pi = 0;  
    bool end = false;

for(int i = 1; i <= MAX; i++)
{
    count = 0;
    for(int j = 2; j <= sqrt(i); j++)
    {
        if(i % j == 0)
        {
            array[i]=0;
            count++;
            break;
        }
    }
    if(count == 0 && i != 1){
        array[i]=1;
    }
}

do {
    cin >> a >> b;
    pi = 0;
    if ((a == 0) && (b == 0)) {
        end = true;
        break;
    }
    else {
        for (int i = a; i <= b; i++) {
            if (array[i] == 1) {
                pi ++;
            }
        }
        cout << pi << endl;
    }
} while (end == false);
cout << endl;

return 0;
}

你可以考虑使用。这是一种高效的素数生成算法。

尝试想象在每个循环步骤上调用sqrt的效率有多高。或者假设编译器有大脑,为什么要用int表示可以保存在bool中的信息。最后,我看不到需要逐级乘法器的代码。你熟悉a吗?这个程序不接受输入吗?为什么不在网上打印一个固定的素数列表呢?@phs我不是想打印一个素数列表,而是要确定在给定范围内有多少素数。@WhozCraig不,我不熟悉Eratosthenes筛,但我会寻找它。谢谢大家!@WhozCraig肯定需要某种优质筛子。但他可能更喜欢Atkin的筛子,这应该是Eratosthenes筛子的优化版本,看我在上面。非常感谢。