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
作业记录。这次的代码依旧不简洁且丑陋 嗐。
#include<stdio.h>
#include<math.h>
int main(void){
int n,i=3,r=1,p=1;
scanf("%d",&n);
int prime[n];
//输出n个素数
prime[0]=2;prime[1]=3;
double a=0;
printf("%d",2);
if(n==1)return 0;
//如果只要输出2,就直接搞定吧
//主要是偶数放进下面的循环会变复杂一些
for(i=5;;i+=2){
int c=0;
a=sqrt(i);
while(prime[c]<=a){
r=i%prime[c];
if(r==0)break;
c++;
}
//上面的步骤是在判断素数
if(r!=0){
p++;
prime[p]=i;
}
if(p>n)break;
}
//输出3以后的素数
for(p=1;p<n;p++)printf(" %d",prime[p]);
printf("\n");
return 0;
}