PAT Grade B 1013 prime numbers (20 points) (C language + detailed notes)

Let P​i​​ denote the i-th prime number. Incumbent give two positive integers M≤N≤10​4​​, please output all prime numbers from P​M​​ to P​N​​.

Input format:

Enter M and N in one line, separated by spaces.

Output format:

Output all prime numbers from P​M​​ to P​N​​. Every 10 digits occupies a line, separated by spaces, but there must be no extra spaces at the end of the line.

Input sample:

5 27

Sample output:

11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103

//The idea of ​​this question is not difficult to think of, directly go to the code of the AC:

#include<stdio.h>

#define MAX 1000000      //第10000个素数是104729,适当把范围开大点,不知道的话在后面多加几个0,只要别超内存即可
int isprime(int p);

int main() {
    int m, n, i, cnt;
    cnt = 0;
    scanf("%d %d", &m, &n);
    for (i = 2; i <= MAX; i++) {
        if (isprime(i)){
            cnt++;             //cnt为第几个素数
            if (cnt >= m) {          //cnt >= m时,即可输出
                int k = cnt - m + 1;
                printf("%d", i);         //先输出这个素数,后面是空格还是换行再判
                if (cnt == n)           //如果已经找到第n个素数了,直接跳出循环
                    break;
                printf("%s", k % 10 ? " " : "\n");     //每10个换行,数字之间为空格
            }
        }
    }
 
    return 0;
}

如果对埃拉托色尼筛法感兴趣的话,详见https://blog.csdn.net/qq_45472866/article/details/104051475

int isprime(int p) {          //判断p是否是素数,我一开始用的埃式筛法(怕超时,因为n最大为10000),AC了,后来我试试直接用这种做法,也AC了,出题者还是挺善良的(没有卡时间)
    if (p < 2)
        return 0;
    int i;
    for (i = 2; i * i <= p; i++)
        if (p % i == 0)
            return 0;
    return 1;
}


 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_45472866/article/details/104207589