题目1:对于给定的一个大于 1 的正整数 N(你可以认为测评机给出的 N 均小于 1000),按从小到大的顺序输出所有小于等于它的质数。输出格式请按从小到大的顺序输出所有小于等于 N 的质数,一个数单独占一行。
2也是质数,不要遗忘
#include <stdio.h>
int prime(int x){
int i;
for(i=3;i*i<x;i+=2)
if(x%i==0)
return 0;
return 1;
}
int main() {
int i;
int j;
int N;
scanf("%d",&N);
if(N>=2){
printf("2\n");
}
for(i=3; i<=N; i+=2){
if(prime(i)){
printf("%d\n",i);
}
}
return 0;
}
题目2指定质数范围
N 一定大于 M,请按从小到大的顺序输出所有小于等于 N 且大于等于 M 的质数。
样例输入
3
5
样例输出
5
7
11
13
17
19
23
29
#include <stdio.h>
#include <string.h>
int n = 1000000;
int mark[1000001];
int main() {
int c, N, M, j;
scanf("%d %d", &N, &M);
memset(mark, 0, sizeof(mark));//Clear the array
mark[0] = 1;
mark[1] = 1;
for (c = 2; c * c <= n; c++) {
if(mark[c] != 1){
for(j=2; j<=n/c; j++){
mark[c*j] = 1;//Find all the no-prime numbers between c and n, mark them with 1.
}
}
}
for(c=M; c<=N; c++){
if(mark[c] != 1){
printf("%d\n", c); //Output unlabeled numbers, that is, output prime numbers
}
}
return 0;
}