Prime number algorithm

Source: Internet
Author: User

Look at the empty blog do not know what to write, write some previous experience it

The prime algorithm compares the common use, this time writes it.

Here I'm giving my usual notation.

Notation 1:

intn=10000; intprime[10000];//used to store prime numbers    intnum=0; intJ;  for(intI=2; i<=n;i++){         for(j=2; j<=sqrt (i); j + +) {//The inner layer just loops to sqrt (i).            if(i%j==0)                 Break; }        if(J>sqrt (i)) prime[num++]=i;

There are not too many good places to talk about, on these lines, the idea is very simple, just the most basic inner loop j<=n replaced with J<=sqrt[i], small optimized a bit

Notation 2: Prime sieve

     int num=0; 
    int n=10000;
    int prime[10000];                   //For storing prime numbers
    int flag[10005];                    //To determine if I is a prime number
    memset (flag,0,sizeof (flag));
    for (int i=2;i<=n;i++) {
        if (flag[i]==0) {
            prime[num++]=i;
            for (int j = i+i; j<=n; j+=i)
                 flag[j]=1;
       }
   }

A very common algorithm, the idea is very simple, each found a prime number, the multiplier of its sieve off (because it is certainly not a prime number), so that time complexity is reduced to linear, so also called the linear prime sieve method

Prime number algorithm

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.