我编写了以下代码来生成从1到n的素数。
为了生成n个素数,应该对此代码进行哪些更改?
例如,如果输入为n=10
,那么素数列表将为:
2,3,5,7,11,13,17,19,23,29
#include <stdio.h>
int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = getValueFromUser();
PrintListOfPrime(value);
return 0;
}
/* Reads a number from user */
int getValueFromUser() {
int value;
printf("Please enter the value of n: ");
scanf("%d", &value);
return value;
}
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");
}