Prime number Screening Method

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.