Closed. This question needs to be more focused. It is not currently accepting answers. Learn more
想改进这个问题吗?更新问题,使其只关注一个问题editing this post
两年前关闭。
我必须计算从0到N之间的质数,问题是当N>100000时程序运行非常缓慢。
int main(){

long int  i, j, n,isPrime;
long int N, count;

N = 10000000;



count = 0;
for(i = 2; i <= N; i++){
    isPrime = 0;

    for(j = 2; j <= i/2; j++){

         if(i % j == 0){
            isPrime = 1;

             break;
         }
    }
     if(isPrime==0 && N!= 1)


     /*printf("%d ",i);*/
     if(isPrime==0 && N!= 1)
    count++;

}

    printf(" %li ", count);
   getch();
   return 0;
 }

最佳答案

你不必上到i/2去寻找素数,只要上到平方根。任何大于平方根的除数都是无用的:你以前就已经找到了它们的对应项。

int sqr = int(sqrt(i));  // make sure it is computed only once
for(j = 2; j <= sqr; j++){

应该可以。。。
或者(如建议的那样)比较正方形以避免计算sqrt
for(j = 2; j*j <= i; j++){

这种方法很好地发现一个大数是否是素数。但要找到一系列素数,最好使用Sieve of Erathostenes算法(我链接了C版本)。

关于c - 如何使C程序运行更快? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42073480/

10-09 13:16