{ "data": { "question": { "questionId": "204", "questionFrontendId": "204", "boundTopicId": null, "title": "Count Primes", "titleSlug": "count-primes", "content": "
Given an integer n
, return the number of prime numbers that are strictly less than n
.
\n
Example 1:
\n\n\nInput: n = 10\nOutput: 4\nExplanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.\n\n\n
Example 2:
\n\n\nInput: n = 0\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: n = 1\nOutput: 0\n\n\n
\n
Constraints:
\n\n0 <= n <= 5 * 106
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
", "As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better?
", "Let's write down all of 12's factors:
\r\n\r\n2 × 6 = 12\r\n3 × 4 = 12\r\n4 × 3 = 12\r\n6 × 2 = 12\r\n\r\n\r\n
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
\r\n\r\nOur total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
\r\n\r\n\r\npublic int countPrimes(int n) {\r\n int count = 0;\r\n for (int i = 1; i < n; i++) {\r\n if (isPrime(i)) count++;\r\n }\r\n return count;\r\n}\r\n\r\nprivate boolean isPrime(int num) {\r\n if (num <= 1) return false;\r\n // Loop's ending condition is i * i <= num instead of i <= sqrt(num)\r\n // to avoid repeatedly calling an expensive function sqrt().\r\n for (int i = 2; i * i <= num; i++) {\r\n if (num % i == 0) return false;\r\n }\r\n return true;\r\n}\r\n", "
The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
\r\n\r\n\r\n
\r\nSieve of Eratosthenes: algorithm steps for primes below 121. \"Sieve of Eratosthenes Animation\" by SKopp is licensed under CC BY 2.0.\r\n
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well?
", "4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be 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 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off?
", "In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 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 p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition?
", "It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3?
", "Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
\r\n\r\nThe Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
\r\n\r\n\r\npublic int countPrimes(int n) {\r\n boolean[] isPrime = new boolean[n];\r\n for (int i = 2; i < n; i++) {\r\n isPrime[i] = true;\r\n }\r\n // Loop's ending condition is i * i < n instead of i < sqrt(n)\r\n // to avoid repeatedly calling an expensive function sqrt().\r\n for (int i = 2; i * i < n; i++) {\r\n if (!isPrime[i]) continue;\r\n for (int j = i * i; j < n; j += i) {\r\n isPrime[j] = false;\r\n }\r\n }\r\n int count = 0;\r\n for (int i = 2; i < n; i++) {\r\n if (isPrime[i]) count++;\r\n }\r\n return count;\r\n}\r\n" ], "solution": { "id": "1130", "canSeeDetail": false, "paidOnly": true, "hasVideoSolution": false, "paidOnlyVideo": true, "__typename": "ArticleNode" }, "status": null, "sampleTestCase": "10", "metaData": "{\r\n \"name\": \"countPrimes\",\r\n \"params\": [\r\n {\r\n \"name\": \"n\",\r\n \"type\": \"integer\"\r\n }\r\n ],\r\n \"return\": {\r\n \"type\": \"integer\"\r\n }\r\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"
Compiled with clang 11
using the latest C++ 17 standard.
Your code is compiled with level two optimization (-O2
). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.
Most standard library headers are already included automatically for your convenience.
\"], \"java\": [\"Java\", \" OpenJDK 17
. Java 8 features such as lambda expressions and stream API can be used.
Most standard library headers are already included automatically for your convenience.
\\r\\nIncludes Pair
class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.
Python 2.7.12
.
Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.
\\r\\n\\r\\nFor Map/TreeMap data structure, you may use sortedcontainers library.
\\r\\n\\r\\nNote that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.
\"], \"c\": [\"C\", \"Compiled with gcc 8.2
using the gnu99 standard.
Your code is compiled with level one optimization (-O1
). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.
Most standard library headers are already included automatically for your convenience.
\\r\\n\\r\\nFor hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:
\\r\\n\\r\\n1. Adding an item to a hash.\\r\\n
\\r\\nstruct hash_entry {\\r\\n int id; /* we'll use this field as the key */\\r\\n char name[10];\\r\\n UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n\\r\\n\\r\\n\\r\\n
2. Looking up an item in a hash:\\r\\n
\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n struct hash_entry *s;\\r\\n HASH_FIND_INT(users, &user_id, s);\\r\\n return s;\\r\\n}\\r\\n\\r\\n\\r\\n\\r\\n
3. Deleting an item in a hash:\\r\\n
\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n HASH_DEL(users, user); \\r\\n}\\r\\n\\r\\n\"], \"csharp\": [\"C#\", \"\\r\\n\\r\\n
Your code is compiled with debug flag enabled (/debug
).
Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor Priority Queue / Queue data structures, you may use datastructures-js/priority-queue and datastructures-js/queue.
\"], \"ruby\": [\"Ruby\", \"Ruby 3.1
Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms
\"], \"swift\": [\"Swift\", \"Swift 5.5.2
.
Go 1.17.6
.
Support https://godoc.org/github.com/emirpasic/gods library.
\"], \"python3\": [\"Python3\", \"Python 3.10
.
Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.
\\r\\n\\r\\nFor Map/TreeMap data structure, you may use sortedcontainers library.
\"], \"scala\": [\"Scala\", \"Scala 2.13.7
.
Kotlin 1.3.10
.
Rust 1.58.1
Supports rand v0.6\\u00a0from crates.io
\"], \"php\": [\"PHP\", \"PHP 8.1
.
With bcmath module
\"], \"typescript\": [\"Typescript\", \"TypeScript 4.5.4, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2020 features.
lodash.js library is included by default.
\"], \"racket\": [\"Racket\", \"Run with Racket 8.3
.