The prime number filter is to filter out all primes in a certain interval [M, n], and the common methods include the following:
1. Simple method of screening:
First write the Judgment function IsPrime (), and then the number in the interval to call IsPrime () to judge, the core of the algorithm is the 2~ square root n as the divisor.
#include <math.h>BOOLIsPrime (intN) { /*sqrt in C + + has two overloaded functions, the argument can be double or float, because the incoming parameter is int, in the default implicit type conversion, int can be converted to float and can be converted to double, then you have to tell the compiler which function to call through a strong turn. */ intSqr = (int) sqrt (Double(n)); for(inti =2; I <= Sqr; i++) { if(N%SQR = =0) return false; } return true;}
2. Efficient Screening Method:
With an array of tokens, for 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 ... The initial prime number is marked, simulating the process of culling composite as follows:
From the beginning of the interval, if the current m is marked as a prime number, then 2*m, 3*m, 4*m ... Are marked as composite, and if M is marked as composite, skip to continue to investigate m+1 ... When the entire interval has been fully examined, all prime and composite control marker arrays are at a glance.
Study 2 o'clock: 2,3,5,7,9,11,13,15,17,19,21,23 ...
Study 3 o'clock: 2,3,5,7,11,13,17,19,23 ...
Study 5 o'clock: 2,3,5,7,11,13,17,19,23 ...
Study 7 o'clock: 2,3,5,7,11,13,17,19,23 ...
......
Prime number Screening Method