我对编程相当陌生,我想尝试编写一个程序来查找一系列数字中素数的数量。当我通过编译器运行该程序时,我没有收到任何错误,但是当我尝试实际运行该程序时,它说只有 2 个,这是不正确的。我认为应该是 168 左右。如果您能帮助指出我的错误,我将不胜感激。提前致谢!
#include <stdio.h>
#include <math.h>
void primeFinder(void);
int main(void)
{
printf("Prime numbers from 1 to 1000:\n\n");
primeFinder();
return 0;
}
void primeFinder(void)
{
int i;
int j;
int k;
int n_primes = 0;
//i is the number to be tested:
for ( i = 2 ; i <= 1000 ; i++ )
{
//i must be divided by j, that goes from 2 to i - 1 [(i - 2) divisions]:
for ( j = 2, k = 0 ; j <= sqrt(i) ; j++ )
{
//i is not prime, whatever is the value of j:
if ( i % j == 0 )
{
//If remainder is 0, there is no need to test that i anymore:
break;
}
else
{
k++;
}
} //End of inner for
//i is prime:
if ( k == i - 2 )
{
printf("%d\t", i);
n_primes++;
}
} //End of outer for
printf("\n\nIt was found %d prime(s) in the inverval considered.\n", n_primes);
}