[Arrays]D. Liang 6.6 Revising Listing 4.11.c

Description

Listing 4.11 determines whether a number n is prime by checking whether 2, 3, 4, 5, 6, …, n/2 is a divisor. If a divisor is found, n is not prime. A more efficient approach to determine whether n is prime is to check whether any of the prime numbers less than or equal sqrt(n) can divide n evenly. If not, n is prime. Rewrite 4.11 to display the first fifty prime numbers using this approach. You need to use an array to store the prime numbers and later use them to check whether they are possible divisors for n.

Input

An integer n (1<=n<=10000).

Output

The first n prime number with one blank to seperate them. Don’t output blank after the last prime number, output “\n” instead.

Sample Input

12

Sample Output

2 3 5 7 11 13 17 19 23 29 31 37

My code:

//   Date:2020/4/18
//   Author:xiezhg5 
#include <stdio.h>
//普通判断质数的方法很容易超时
//这里给出优化之后的方法
void getNPrimes_optimize();
int main(void)
{
    getNPrimes_optimize();
    return 0;
}
//优化之后的方法
void getNPrimes_optimize(){
    int count;
    scanf("%d",&count);
    //使用数组来保存所求出的质数
    int primes[count];
    /**
     * 首先,第一个已知的质数是2,
     * 则计算应该从3开始
     */
    primes[0] = 2;
    int pc = 1;
    int m =3; //从数字3开始
    while(pc < count){
        int k = 0;
        // 这里只要找不到质数,就会一直在这个循环中
        while(primes[k] * primes[k] <= m){
            if(m % primes[k] == 0){
                m += 2; //除了数字2之外,其他所有的质数都是奇数
                k = 1; //不用使用数字2去测试
            }else{
                k++;
            }
        }
        //找到质数之后,跳出上面的循环
        //这个的执行是先执行primes[pc] = m;
        //再去执行pc++;
        primes[pc++] = m;
        m+=2;
    }
    /**
     * 对质数进行输出操作
     *
     */
    for(pc = 0;pc < count;pc++){
        printf("%d ",primes[pc]);
    }
}
发布了245 篇原创文章 · 获赞 255 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/105602726