Leetcode:count Primes

Source: Internet
Author: User

Count Primes


Total Accepted: 65068 Total Submissions: 263838 Difficulty: Easy

Description:

Count the number of prime numbers less than a non-negative number, n.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Hint:

  1. Let's start with a isprime function. To determine if a number is the prime, we need to check if it isn't divisible by any number less than n. The runtime complexity of IsPrime function would is O (n) and hence counting the total prime numbers up t o n would be O (n2). Could We do better?

  2. As we know the number must not being divisible by no number > n /2, we can immediately cut the total iterations Half by dividing-up ton /2. Could we still do better?

  3. Let's write down all of the factors:

    2x6 = 123x4 = 124x3 = 126x2 = 12

    As can see, calculations of 4x3 and 6x2 is not necessary. Therefore, we only need to consider factors up to√n because, if n are divisible by some number P then n = p x Q and since p ≤ Q, we could derive that p ≤√n .

    Our total runtime have now improved to O (n1.5), which is slightly better. Is there a faster approach?

    public int countprimes (int n) {int count = 0;   for (int i = 1; i < n; i++) {if (IsPrime (i)) count++; } return count;}   Private boolean isprime (int num) {if (num <= 1) return false; Loop ' s ending condition is i * I <= num instead of i <= sqrt (num)//To avoid repeatedly calling an expensive F   Unction sqrt ().   for (int i = 2; I * i <= num; i++) {if (num% i = = 0) return false; } return true;} 
  4. The Sieve of Eratosthenes is one of the most efficient ways to find all primes numbers up to N. But don ' t let that name scare you, I promise that the concept is surprisingly simple.


    Sieve of eratosthenes:algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by Skopp are licensed under CC by 2.0.

    we start off with a table Of n  numbers . Let's look at the first number, 2. We know all multiples of 2 must is not being primes, so we mark them off as Non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3x2 = 6, 3x3 = 9, ... must not being primes, so we mark them off as well. Now we look at the next number, 4, which is already marked off. What is does this? Should you mark off all multiples of 4 as well?

  5. 4 is not a prime Because it is divisible by 2, which means all multiples of 4 must also being divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5x2 = ten, 5x3 =, 5x4 =, 5x5 = ... can be marked off. There is a slight optimization here, we don't need to start from 5x2 = 10. Where should we start marking off?

  6. in fact, we can mark Off multiples of 5 starting at 5x5 = $, because 5x2 = Ten was already marked off by multiple of 2, similarly 5x3 = 1 5 was already marked off by multiple of 3. Therefore, if the current number Is p , we can always mark off multiples Of  P  starting at p 2 , then in increments Of p :  p 2  + p ,  p 2  + 2p , ... What is should be the terminating loop condition?

  7. It's easy to say the terminating loop condition are p < n, which is certainly correct and not EF Ficient. Do you still remember Hint #3?

  8. Yes, the terminating loop condition can is p <√n, as all non-primes≥√n must has already been marked off. When the loop is terminates, all of the numbers in the table is non-marked is prime.

    the Sieve of Eratosthenes uses an extra O (n ) Memory and its runtime complexity is O (n  log log 

    public int countprimes (int n) {   boolean[] IsPrime = new Boolean[n];   for (int i = 2; i < n; i++) {      Isprime[i] = true;   }   Loop ' s ending condition are i * I < n instead of I < sqrt (n)   //To avoid repeatedly calling an expensive funct Ion sqrt ().   for (int i = 2; I * i < n; i++) {      if (!isprime[i]) continue;      for (int j = i * i; j < n; j + = i) {         isprime[j] = false;      }   }   int count = 0;   for (int i = 2; i < n; i++) {      if (isprime[i]) count++;   }   return count;}

Subscribe to see which companies asked this question

Hide TagsHash Table MathHide Similar Problems(E) Ugly number (m) Ugly number II (m) Perfect squares







































































































Ideas:

Prime Sieve method.


C + + code:

Class Solution {public:    int countprimes (int n) {        bool isprime[n];        for (int i=2;i<n;i++)            isprime[i]=true;                    for (int i=2;i*i<n;i++) {            if (!isprime[i]) continue;                        for (int j=i*i;j<n;j+=i)                isprime[j]=false;        }        int cnt=0;        for (int i=2;i<n;i++)            if (isprime[i]) cnt++;                    return cnt;    }};


Leetcode:count Primes

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.