质数计算器。这些都正确吗?

Prime number calculator. Are these both correct?

一直在尝试编写显示素数的程序,只是想知道以下两种算法之间是否存在很大差异。

1,

#include <stdio.h>
#define MAXNUMB 100000

int main(void){
   int flag;
   long i,j=MAXNUMB;
   printf ("The Prime Numbers up to %ld are:\n       2\n", j);
   for(i=3 ; i<=MAXNUMB; i = i+2){
       j = 3;           //only difference is in this line
       flag = 0;
       while((j*j <= i) && flag == 0){
            if(i%j == 0){
                flag = 1;
            }
            j++;
      }
      if (flag == 0){
         printf("%8ld\n",i);
      }
  }
}

2,

  #include <stdio.h>
  #define MAXNUMB 100000

  int main(void){
     int flag;
     long i,j=MAXNUMB;
     printf ("The Prime Numbers up to %ld are:\n       2\n", j);
     for(i=3 ; i<=MAXNUMB; i = i+2){
        j = 2;       //again this is the only different line
        flag = 0;
        while((j*j <= i) && flag == 0){
             if(i%j == 0){
                flag = 1;
            }
            j++;
    }
    if (flag == 0){
        printf("%8ld\n",i);
    }
 }
}

在我看来,两者都有效,但我不确定,也许有人可以解释一下。

此外,对于开始编码的人,有任何适用于所有程序员的一般技巧吗?

谢谢!

它们都有相同的输出,因为您使用 i = i + 2 跳过偶数并使用 i = 3 开始循环。所以 i % j == 0 条件在 j = 2 时永远不会为真。

To me it seems like they have the same output but i cant check every number

将您的方法包装到单独的函数中,return将结果放在一个数组中,然后比较两个数组。

您可以使用 GNU/Linux 或 Cygwin 的内置 time 函数快速查看完成这些操作所需的时间。使用 G++ 编译器,第一个片段大约需要 0.109s 到 运行,第二个片段大约需要 0.141s 到 运行。所以我想这取决于您对 "more efficient" 的定义。注意:我没有检查结果的准确性,只是 运行按原样调整程序。

至于一般的编程技巧,你在互联网上可以访问无限的信息,只需搜索编程技巧。可以为初学者写一本关于 "tips" 的书。 Here 就是一个很好的例子。