Efficient search for prime--sieve of Eratosthenes

Source: Internet
Author: User

Sieve of Eratosthenes-Eratosthenes sieve, referred to as the sieve.

Idea: give the range of values to sieve N, find the prime number within . First use 2 to sift, that is, 2 left, the number of 2 is removed, and then the next prime, that is, 3 sieve, 3 left, the multiples of 3 is removed, then the next prime number of 5 sieve, 5 left, the multiples of 5 are removed; Keep repeating ... until it is less than equals.

As follows:





Example: A problem with searching for prime numbers on Leetcode (https://leetcode.com/problems/count-primes/).

Question:Count The number of prime numbers less than a non-negative number, n

PS: When the N=1500000,leetcode evaluation is 58ms, the operating efficiency is good in C + +.

int countprimes (int n) {    bool isprimes[n];    int primesnum=0;    for (int i=2; i<n; i++)        isprimes[i]=true;    Remove the times of primes.    for (int i=2; i<=sqrt (n), i++)        if (Isprimes[i]) for            (int j=2; j*i<=n; j + +)                Isprimes[j*i]=false;    The count of primes.    for (int i=2; i<n; i++)        if (Isprimes[i])            primesnum++;    return primesnum;}

Efficient search for prime--sieve of Eratosthenes

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.