我试图用C语言编写程序以打印所有从2到给定编号的素数。
#include <stdio.h>
#include <math.h>
int main() {
int up, t = 1, i, j;
puts("This program will show you a list of all prime numbers from 2 to the number you enter below: ");
scanf("%d", &up);
for(i == 2; i <= up; i++) {
for(j == 1; j <= sqrt(i); j++) {
if(i % j != 0) {
t = 0;
}
if(t == 1) {
printf("%d", i);
}
}
}
return(0);
}
返回以下结果:
$ gcc prime.c -lm
$ ./a.out
This program will show you a list of all prime numbers from 2 to the number you enter below:
10
我的意思是,输入10后,程序终止。有想法吗?谢谢。
这里是程序的可能的固定版本。
使用此代码:-