题目链接:https://leetcode.com/problems/count-primes/
Description:
Count the number of prime numbers less than a non-negative number, n.
Given an integer n
, return the number of prime numbers that are strictly less than n
.
Example 1:
Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0 Output: 0
Example 3:
Input: n = 1 Output: 0
依乐托斯然尼斯质数筛法
假设这个范围是从2到300,做法是从2开始,在2到300之间把所有2的倍数但不等于2的数都划掉;接着就要划掉下一个,也就是3,在所有2到300之间划掉是3的倍数但不等于3的数;接着要划掉下一个数,也就是5,在2到300之间把所有是5的倍数但不等于5的数都划掉。以此类推。在每个阶段,下一个数一定是质数。在这些步骤的最后,当300以下再也没有数字被删掉,每一个剩下的数就是质数。(以300以内的质数为例,一旦17的倍数(非17本身)划掉之后,这个步骤就停止。因为任何两个大于17的质数乘积一定大于300。)。
#include <vector>
using namespace std;
class Solution {
public:
// Function to count prime numbers less than n
int countPrimes(int n) {
// Create a vector to store whether each number is prime
// Initialize all numbers as potential primes
vector<int> prime(n + 1, 1);
// Sieve of Eratosthenes algorithm
for (int i = 2; i * i <= n; i++) {
// If i is prime
if (prime[i] == 1) {
// Mark all multiples of i as non-prime
for (int j = i * i; j <= n; j += i) {
prime[j] = 0;
}
}
}
// Count the number of primes
int ans = 0;
for (int i = 2; i < n; i++) {
if (prime[i] == 1)
ans++;
}
return ans;
}
};