【发布时间】:2020-11-10 16:45:45
【问题描述】:
我写了这个程序来查找 1 到 50000 之间的素数,但我仍然需要找出有多少个素数(我尝试了很多技巧,但我没有成功)
#include <stdio.h>
//int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = 23;
PrintListOfPrime(value);
return 0;
}
void PrintListOfPrime(int value) {
int ValueIsPrime; //ValueIsPrime is used as flag variable
printf("The list of primes: ");
for (int i = 2; i <= value; i++) {
ValueIsPrime = 1;
/* Check if the current number i is prime or not */
for (int j = 2; j <= i / 2; j++) {
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if (i % j == 0) {
ValueIsPrime = 0;
break;
}
}
/* If the number is prime then print */
if (ValueIsPrime == 1)
printf("%d, ", i);
}
printf("\n");
}
【问题讨论】:
-
如果你能列出素数,你不能只增加一个计数器而不是打印所说的素数吗?
-
“我尝试了很多技巧但我没有成功”是模糊的。怎么没成功?
-
@Chouiba Zahira 有 5133 个素数,直到 50000。
标签: c loops for-loop primes function-definition