Eratosthenes filter to calculate prime
"In addition to itself, can not be divisible by other integers," called prime numbers, the requirement is simple, but how to quickly find the prime number is always a programmer and mathematician efforts of the subject, on this side to introduce a well-known eratosthenes to find the prime method. Solution
The first thing to know is that this problem can be solved by using loops, dividing a specified number by all the number less than it, and if it can be divided, it is not prime, but how to reduce the number of times the cycle is checked. How to find all the prime numbers less than N.
Let's assume that the number you want to check is N good, in fact, as long as the check to the N of the open root can be, the reason is very simple, assuming a*b = N, if a is greater than N of the open root, then in fact, before a check is less than a can be checked to B this number can divide N. However, the use of the open root in the program is accurate, so you can use I*i <= N to check and perform faster.
Again assume that there is a sieve for storing 1~n, for example: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ... N
First, the multiple of 2 is screened: 2 3 5 7 9 11 13 15 17 19 21 ... N
Then sieve the 3 multiples: 2 3 5 7 11 13 17 19 ... N
Then sift the 5 multiples, then sift the 7 prime numbers, then sift the multiples of 11 ... so that the last number left is prime, and this is the Eratosthenes filtering method (Eratosthenes sieve methods).)
The number of checks can be reduced, in fact, as long as the check 6n+1 and 6n+5 on it
Python code:
def findallprime (n):
pt=[true]*n
prime=[] for
p in range (2,n):
if not pt[n]:continue
Prime.append (p)
for I in range (p*p,n,p)
pt[i]=false return
Prime, PT
Prime,pt=findallprime (10000)
C + + code:
const int N = 10000;
BOOL Arrprimetable[n + 1];
int ncount = 0;
void Initprimetable ()
{
//initialization for
(int i = 2;i <= n;i++)
{
Arrprimetable[i] = true;
}
To exclude for
(i = 2;i * I <= n;i++)
{
if (Arrprimetable[i])
{
//To remove the multiple of I: t = x * I for
(int t = i + i;t <= n;t + = i)
{
Arrprimetable[t] = False
;
}}} Output for
(i = 2;i <= n;i++)
{
if (Arrprimetable[i])
{
cout<<i<< "";
ncount++;
if (ncount%10==0)
cout<<endl;
}
}
cout<<endl<< "Total:" <<nCount<< "a" <<endl;
}
Or you can use this method, the prime number can only be around 6,
That is: num% 6 = 1 or num% 6 = 5
Proof, Disprove: If num%6 can equal 2,3,4
6x+2,6x+3,6x+4 can extract 2 or 3
that is, 2 (x+1) is not a prime number
BOOL IsPrime (int num)
{
if (num = 2 | | | num = 3)
{return
true;
}
if (num% 6!= 1 && num% 6!= 5)
{return
false;
}
for (int i = 5; i*i <= num. i = 6)
{
if (num% i = = 0 | | | num% (i+2) = = 0)
{return
false;
}
}
return true;
}