1, the following is the general method to find the prime number of 1~n:
The general method of finding the prime number of 1~n
#include <iostream>
using namespace std;
int main ()
{
int n,i,j,k=1;
bool Bo;
cin>>n;cout<< "2";
for (i=3;i<=n;i+=2)
{
bo=true;
for (j=3;j*j<=i;j+=2)
if (i%j==0)
{
bo=false;
break;
if (bo)
{
if (k%10==0) cout<<endl;
cout<<i<< ';
k++
}
}
cout<<endl<<k<<endl;
return 0;
}
2, for the number of prime screening method, the specific method is not elaborated, Baidu can be found, simply say is to find a prime number of its multiples marked as a non prime.
Reference code:
The prime
#include <iostream>
using namespace std
of 1~n were obtained by the method of number selection. #define N 1000000000
bool Isprime[n];
int prime[100000];
int main ()
{
int n,i,j,k=1;
memset (isprime,true,sizeof (IsPrime));
cin>>n;
int num=0;
prime[num++]=2;
for (i=3;i<=n;i+=2)
{
if (Isprime[i])
{
prime[num++]=i;
for (j=i+i;j<=n;j+=i)
isprime[j]=false;
}
}
for (i=0;i<num;i++)
{
cout<<prime[i]<< ';
if ((i+1)%10==0)
cout<<endl;
}
cout<<endl<<num<<endl;
return 0;
}
3, the following is my small optimization of the algorithm:
is to change the for (j=i+i; j<=n j+=i) to for (J=i*i; j<=n; j+=2*i) because 2*i is a multiple of 2, 3*i is a multiple of 3, and 5*i is a multiple of 5 ~~~~~~, so J directly Starting from I*i, and every time J 2*i,
This will eliminate the even number. After modification, you can reduce the amount of duplicate assignments.
Complete code:
#include <iostream>
using namespace std;
#define N 1000000000
bool Isprime[n];
int prime[100000];
int main ()
{
int n,i,j,k=1;
memset (isprime,true,sizeof (IsPrime));
cin>>n;
int num=0;
prime[num++]=2;
for (i=3;i<=n;i+=2)
{
if (Isprime[i])
{
prime[num++]=i;
for (j=i*i;j<=n;j+=2*i)
isprime[j]=false;
}
}
for (i=0;i<num;i++)
{
cout<<prime[i]<< ';
if ((i+1)%10==0)
cout<<endl;
}
cout<<endl<<num<<endl;
return 0;
}