有没有办法在过滤非素数后打印素数本身和总计数?
Is there a way to print the prime number itself and the overall count after having filtered non-prime?
我有下面的代码并且有注释。它本质上是基于 'Sieve of Eratosthenes.' 我正在修改它以在代码的最后一个 for 循环中打印和计算剩余的质数。但是,输出是“1There are 1 primes.”
#include <stdio.h>
#define SIZE 50000
int main(void) {
int i, mult, count, count2;
int flag[SIZE + 1];
count = 0;
count2 = 0;
//sets up all numbers
for (i = 1; i <= SIZE; i++) {
flag[i] = 1;
//printf("%d",flag[i]);
}
//step 1: selects the prime number
for (i = 2; i <= SIZE; ++i) {
if (flag[i] == 1)
++count;
mult = i;
//step 2: filters out numbers multiple of that prime number in step 1
while (mult <= SIZE) {
flag[mult] = 0;
mult = mult + i;
}
}
//Now that the non-prime numbers have been filtered, this then prints the number and counts the prime numbers
for (i = 1; i <= SIZE; i++) {
if (flag[i] == 1) {
++count2;
printf("%d", i);
}
}
printf("There are %d primes. \n", count2);
return 0;
}
在你的第二个 for 循环中,你开始于:
mult = i;
然后在 while 中,就在您设置之后:
flag[mult] = 0;
本质上你说这个数不是素数。
如果将行 mult = i 替换为:
mult = i + i ;
那么你的程序运行正常了。
我有下面的代码并且有注释。它本质上是基于 'Sieve of Eratosthenes.' 我正在修改它以在代码的最后一个 for 循环中打印和计算剩余的质数。但是,输出是“1There are 1 primes.”
#include <stdio.h>
#define SIZE 50000
int main(void) {
int i, mult, count, count2;
int flag[SIZE + 1];
count = 0;
count2 = 0;
//sets up all numbers
for (i = 1; i <= SIZE; i++) {
flag[i] = 1;
//printf("%d",flag[i]);
}
//step 1: selects the prime number
for (i = 2; i <= SIZE; ++i) {
if (flag[i] == 1)
++count;
mult = i;
//step 2: filters out numbers multiple of that prime number in step 1
while (mult <= SIZE) {
flag[mult] = 0;
mult = mult + i;
}
}
//Now that the non-prime numbers have been filtered, this then prints the number and counts the prime numbers
for (i = 1; i <= SIZE; i++) {
if (flag[i] == 1) {
++count2;
printf("%d", i);
}
}
printf("There are %d primes. \n", count2);
return 0;
}
在你的第二个 for 循环中,你开始于:
mult = i;
然后在 while 中,就在您设置之后:
flag[mult] = 0;
本质上你说这个数不是素数。
如果将行 mult = i 替换为:
mult = i + i ;
那么你的程序运行正常了。