Count Primes Problem


Description

LeetCode Problem 204.

Given an integer n, return the number of prime numbers that are strictly less than n.

Example 1:

1
2
3
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Example 2:

1
2
Input: n = 0
Output: 0

Example 3:

1
2
Input: n = 1
Output: 0

Constraints:

  • 0 <= n <= 5 * 10^6


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
	int countPrimes(int n) {
		vector<bool> prime(n + 1, true);
		prime[0] = false;
		prime[1] = false;
		for (int i = 2; i * i <= n; i++) {
			if (prime[i]) {
				for (int j = i * i; j <= n; j += i) {
					prime[j] = false;
				}
			}
		}
		
		//counting prime numbers
		int primeCount = 0;
		for (int i = 2; i < n; i++) {
			if (prime[i]) {
				primeCount++;
			}
		}
		return primeCount;
	}
};




Related Posts

Count Primes Problem

LeetCode 204. Given an integer n, return the number of...

Basic Calculator Problem

LeetCode 224. Given a string s representing a valid expression,...

Basic Calculator II Problem

LeetCode 227. Given a string s which represents an expression,...

Add Digits Problem

LeetCode 258. Given an integer num, repeatedly add all its...

Factorial Trailing Zeroes Problem

LeetCode 172. Given an integer n, return the number of...

Rotate Image Problem

LeetCode 48. Determine if a 9 x 9 Sudoku board...