|
| 1 | +--- |
| 2 | +id: count-primes |
| 3 | +title: Count Primes |
| 4 | +sidebar_label: 0204 - Count Primes |
| 5 | +tags: |
| 6 | +- Array |
| 7 | +- Math |
| 8 | +- Enumeration |
| 9 | +- Number Theory |
| 10 | + |
| 11 | +description: "This is a solution to the Count Primes problem on LeetCode." |
| 12 | +--- |
| 13 | + |
| 14 | +## Problem Description |
| 15 | +Given an integer n, return the number of prime numbers that are strictly less than n. |
| 16 | + |
| 17 | +### Examples |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | +``` |
| 21 | +Input: n = 10 |
| 22 | +Output: 4 |
| 23 | +Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. |
| 24 | +
|
| 25 | +``` |
| 26 | +**Example 2:** |
| 27 | +``` |
| 28 | +Input: n = 0 |
| 29 | +Output: 0 |
| 30 | +``` |
| 31 | +**Example 3:** |
| 32 | +``` |
| 33 | +Input: n = 1 |
| 34 | +Output: 0 |
| 35 | +``` |
| 36 | + |
| 37 | +### Constraints |
| 38 | +- `0 <= n <= 5 * 10^6` |
| 39 | + |
| 40 | +## Solution for Count Primes Problem |
| 41 | + |
| 42 | +### Brute Force |
| 43 | +- Iterate through all numbers from 2 up to n-1 (since we need to find primes less than n). |
| 44 | +- For each number, check if it is a prime by counting its divisors. |
| 45 | + |
| 46 | +<Tabs> |
| 47 | + <TabItem value="Brute Force" label="Brute Force"> |
| 48 | + |
| 49 | +#### Implementation |
| 50 | + |
| 51 | +```jsx live |
| 52 | +function primeCounter(n) { |
| 53 | + function isPrime(n) { |
| 54 | + let count = 0; |
| 55 | + if (n === 1) { |
| 56 | + return false; |
| 57 | + } |
| 58 | + for (let i = 1; i < n; i++) { |
| 59 | + if (n % i === 0) { |
| 60 | + count++; |
| 61 | + } |
| 62 | + } |
| 63 | + if (count > 1) { |
| 64 | + return false; |
| 65 | + } |
| 66 | + return true; |
| 67 | + } |
| 68 | + |
| 69 | + function countPrimes(n) { |
| 70 | + let count = 0; |
| 71 | + for (let i = 2; i < n; i++) { |
| 72 | + if (isPrime(i)) { |
| 73 | + count++; |
| 74 | + } |
| 75 | + } |
| 76 | + return count; |
| 77 | + } |
| 78 | + |
| 79 | + const input = 10 |
| 80 | + const output = countPrimes(input) |
| 81 | + return ( |
| 82 | + <div> |
| 83 | + <p> |
| 84 | + <b>Input: </b>{ JSON.stringify(input)} |
| 85 | + </p> |
| 86 | + <p> |
| 87 | + <b>Output:</b> {output.toString()} |
| 88 | + </p> |
| 89 | + </div> |
| 90 | + ); |
| 91 | +} |
| 92 | +``` |
| 93 | +#### Complexity Analysis |
| 94 | + |
| 95 | +- Time Complexity: $ O(n^2) $ is the time complexity, because two nested loops are used , one is from 2 to n and second is used to check whether a number is prime or not which also takes $ O(n)$ complexity |
| 96 | +- Space Complexity: $ O(1) $ |
| 97 | + |
| 98 | + |
| 99 | +### Optimized Approach - Sieve of Eratosthenes Algorithm |
| 100 | +#### Intuition |
| 101 | +The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a given limit n. The basic idea is to iteratively mark the multiples of each prime starting from 2. By the end of the algorithm, the numbers that remain unmarked are prime. |
| 102 | + |
| 103 | +#### Steps |
| 104 | +- Create a list of boolean values: Initialize an array is_prime of size n with all values set to true. is_prime[i] will be true if i is a prime number, false otherwise. |
| 105 | +- Mark non-primes: Starting from the first prime number (2), mark all its multiples as non-prime. Move to the next number and repeat until you've processed numbers up to the square root of n. |
| 106 | +- Count primes: The numbers which remain marked as true in the is_prime array are primes. |
| 107 | + |
| 108 | +#### Code in Different Languages |
| 109 | + |
| 110 | +<Tabs> |
| 111 | + <TabItem value="JavaScript" label="JavaScript"> |
| 112 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 113 | + ```javascript |
| 114 | + function countPrimes(n) { |
| 115 | + if (n <= 2) return 0; |
| 116 | + |
| 117 | + // Step 1: Initialize the array with true values |
| 118 | + let is_prime = new Array(n).fill(true); |
| 119 | + is_prime[0] = is_prime[1] = false; // 0 and 1 are not primes |
| 120 | + |
| 121 | + // Step 2: Mark non-primes |
| 122 | + for (let i = 2; i * i < n; i++) { |
| 123 | + if (is_prime[i]) { |
| 124 | + for (let j = i * i; j < n; j += i) { |
| 125 | + is_prime[j] = false; |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + // Step 3: Count primes |
| 131 | + let count = 0; |
| 132 | + for (let i = 2; i < n; i++) { |
| 133 | + if (is_prime[i]) { |
| 134 | + count++; |
| 135 | + } |
| 136 | + } |
| 137 | + return count; |
| 138 | + } |
| 139 | + |
| 140 | + |
| 141 | + ``` |
| 142 | + |
| 143 | + </TabItem> |
| 144 | + <TabItem value="TypeScript" label="TypeScript"> |
| 145 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 146 | + ```typescript |
| 147 | + function countPrimes(n: number): number { |
| 148 | + if (n <= 2) return 0; |
| 149 | +
|
| 150 | + // Step 1: Initialize the array with true values |
| 151 | + const isPrime: boolean[] = new Array(n).fill(true); |
| 152 | + isPrime[0] = isPrime[1] = false; // 0 and 1 are not primes |
| 153 | +
|
| 154 | + // Step 2: Mark non-primes |
| 155 | + for (let i = 2; i * i < n; ++i) { |
| 156 | + if (isPrime[i]) { |
| 157 | + for (let j = i * i; j < n; j += i) { |
| 158 | + isPrime[j] = false; |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | +
|
| 163 | + // Step 3: Count primes |
| 164 | + let count = 0; |
| 165 | + for (let i = 2; i < n; ++i) { |
| 166 | + if (isPrime[i]) { |
| 167 | + ++count; |
| 168 | + } |
| 169 | + } |
| 170 | + return count; |
| 171 | +} |
| 172 | + ``` |
| 173 | + |
| 174 | + </TabItem> |
| 175 | + <TabItem value="Python" label="Python"> |
| 176 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 177 | + ```python |
| 178 | + def count_primes(n: int) -> int: |
| 179 | + if n <= 2: |
| 180 | + return 0 |
| 181 | +
|
| 182 | + # Step 1: Initialize the array with True values |
| 183 | + is_prime = [True] * n |
| 184 | + is_prime[0] = is_prime[1] = False # 0 and 1 are not primes |
| 185 | +
|
| 186 | + # Step 2: Mark non-primes |
| 187 | + for i in range(2, int(n ** 0.5) + 1): |
| 188 | + if is_prime[i]: |
| 189 | + for j in range(i * i, n, i): |
| 190 | + is_prime[j] = False |
| 191 | +
|
| 192 | + # Step 3: Count primes |
| 193 | + count = sum(is_prime[2:]) |
| 194 | + return count |
| 195 | +
|
| 196 | + ``` |
| 197 | + |
| 198 | + </TabItem> |
| 199 | + <TabItem value="Java" label="Java"> |
| 200 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 201 | +``` |
| 202 | +public class Solution { |
| 203 | + public int countPrimes(int n) { |
| 204 | + if (n <= 2) return 0; |
| 205 | + |
| 206 | + // Step 1: Initialize the array with true values |
| 207 | + boolean[] isPrime = new boolean[n]; |
| 208 | + for (int i = 2; i < n; i++) { |
| 209 | + isPrime[i] = true; |
| 210 | + } |
| 211 | + |
| 212 | + // Step 2: Mark non-primes |
| 213 | + for (int i = 2; i * i < n; i++) { |
| 214 | + if (isPrime[i]) { |
| 215 | + for (int j = i * i; j < n; j += i) { |
| 216 | + isPrime[j] = false; |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + // Step 3: Count primes |
| 222 | + int count = 0; |
| 223 | + for (int i = 2; i < n; i++) { |
| 224 | + if (isPrime[i]) { |
| 225 | + count++; |
| 226 | + } |
| 227 | + } |
| 228 | + return count; |
| 229 | + } |
| 230 | + |
| 231 | + public static void main(String[] args) { |
| 232 | + Solution solution = new Solution(); |
| 233 | + System.out.println(solution.countPrimes(10)); // Output: 4 (primes are 2, 3, 5, 7) |
| 234 | + } |
| 235 | +} |
| 236 | + |
| 237 | +``` |
| 238 | +
|
| 239 | + </TabItem> |
| 240 | + <TabItem value="C++" label="C++"> |
| 241 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 242 | + ```cpp |
| 243 | + int countPrimes(int n) { |
| 244 | + if (n <= 2) return 0; |
| 245 | +
|
| 246 | + // Step 1: Initialize the array with true values |
| 247 | + vector<bool> is_prime(n, true); |
| 248 | + is_prime[0] = is_prime[1] = false; // 0 and 1 are not primes |
| 249 | +
|
| 250 | + // Step 2: Mark non-primes |
| 251 | + for (int i = 2; i * i < n; ++i) { |
| 252 | + if (is_prime[i]) { |
| 253 | + for (int j = i * i; j < n; j += i) { |
| 254 | + is_prime[j] = false; |
| 255 | + } |
| 256 | + } |
| 257 | + } |
| 258 | +
|
| 259 | + // Step 3: Count primes |
| 260 | + int count = 0; |
| 261 | + for (int i = 2; i < n; ++i) { |
| 262 | + if (is_prime[i]) { |
| 263 | + ++count; |
| 264 | + } |
| 265 | + } |
| 266 | + return count; |
| 267 | + } |
| 268 | + ``` |
| 269 | +
|
| 270 | + </TabItem> |
| 271 | + </Tabs> |
| 272 | +
|
| 273 | +#### Complexity Analysis |
| 274 | +- Time Complexity: $ O(N*log(logn))$ |
| 275 | + - Space Complexity: $ O(N)$ |
| 276 | +</TabItem> |
| 277 | +</Tabs> |
| 278 | +
|
| 279 | +## References |
| 280 | +
|
| 281 | +- **LeetCode Problem**: [Count Primes](https://leetcode.com/problems/count-primes/description/) |
| 282 | +
|
| 283 | +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/count-primes/solutions) |
| 284 | +
|
0 commit comments