Last active
December 1, 2018 07:53
-
-
Save qiaoxu123/011ed6487f7a1574e8c8df55af0d78a9 to your computer and use it in GitHub Desktop.
Count the number of prime numbers less than a non-negative number, n.
```
Example: Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
```
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int countPrimes(int n) { | |
if(n <= 2) return 0; | |
vector<bool> passed(n,false); | |
int sum = 1; | |
int upper = sqrt(n); | |
for(int i = 3;i < n;i += 2){ | |
if(!passed[i]){ | |
sum++; | |
//avoid overflow | |
if(i > upper) continue; | |
for(int j = i * i;j < n;j += i){ | |
passed[j] = true; | |
} | |
} | |
} | |
return sum; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment