C语言质数的简单判断和输出

题目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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值