topic description
Find the prime numbers in N.
input format
N
output format
Prime numbers from 0 to N
sample input
100
sample output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Ordinary method idea:
Traverse the numbers within 2~N, and then traverse the one-digit number i in 2~i, see if the number in 2~i can be divisible by i, count by count, if count=0, it means that there is no number that can be divided by i i divisible number, then this number is a prime number, the code is as follows:
#include<stdio.h>
int main()
{
//素数就是除一和本身外没有其他的数能与它本身整除
int i,j,n,count;//count用来记录可以和i整除的数
scanf("%d",&n);
for(i=2;i<=n;i++)
{
count=0;//注意每次都要重新赋零值,不然后面判定就错了
for(j=2;j<i;j++)
{
if(i%j==0) count++;//如果i是素数的话count应该是零的
}
if(count==0) printf("%d\n",i);//如果是素数就就输出了记得要加换行符
}
return 0;
}
Optimization method idea : A method I saw on the Internet is a new idea for me, and I will share it with you here
• Any natural number N greater than 1, if N is not a prime number, then N can be uniquely decomposed into a product of finite prime numbers
•So if prime[i]==0, then prime[i*j]==1, that is, prime[i*j] is not a prime number
Note:
prime[2]==0 means 2 is a prime number prime[8]==1 means 8 is not a prime number
prime[0]=prime[1]=1; //0 and 1 need special handling
code show as below
#include<stdio.h>
int main(){
int prime[10000]={0};
int i,j;
int n;
scanf("%d",&n);
prime[0]=prime[1]=1;
for(i=2;i<n;i++)
if(prime[i]==0)
for(j=2;i*j<=n;j++)
prime[i*j]=1;
for(i=0;i<n;i++)
if(prime[i]==0)
printf("%d\n",i);
return 0;
}