LeetCode //C - 204. Count Primes

204. Count Primes

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

Constraints:
  • 0 < = n < = 5 ∗ 1 0 6 0 <= n <= 5 * 10^6 0<=n<=5∗106

From: LeetCode

Link: 204. Count Primes


Solution:

Ideas:

1. Edge Cases: If n is less than or equal to 2, there are no prime numbers less than n, so we return 0.

2. Initialization: We create an array isPrime of size n and initialize all elements to true. This array will helpus mark non-prime numbers.

3. Sieve of Eratosthenes:

  • For each number i starting from 2 up to the square root of n, if i is still marked as prime (isPrime[i] is true), we mark all its multiples as non-prime.
  • The inner loop starts at i * i because any smaller multiple of i would have already been marked by a smaller prime factor.

4. Counting Primes: After marking non-prime numbers, we iterate through the isPrime array and count how many numbers are still marked as prime.

5. Memory Management: Finally, we free the allocated memory for the isPrime array and return the count of prime numbers.

Code:
c 复制代码
int countPrimes(int n) {
    if (n <= 2) {
        return 0;
    }
    
    bool *isPrime = (bool *)malloc(n * sizeof(bool));
    for (int i = 2; i < n; ++i) {
        isPrime[i] = true;
    }
    
    for (int i = 2; i * i < n; ++i) {
        if (isPrime[i]) {
            for (int j = i * i; j < n; j += i) {
                isPrime[j] = false;
            }
        }
    }
    
    int count = 0;
    for (int i = 2; i < n; ++i) {
        if (isPrime[i]) {
            ++count;
        }
    }
    
    free(isPrime);
    return count;
}
相关推荐
爱编码的傅同学16 分钟前
【今日算法】LeetCode 25.k个一组翻转链表 和 43.字符串相乘
算法·leetcode·链表
stolentime16 分钟前
P14978 [USACO26JAN1] Mooclear Reactor S题解
数据结构·c++·算法·扫描线·usaco
hjjdebug17 分钟前
switch-case 语句分析(消灭swich-case方法)
c语言·switch-case
老歌老听老掉牙21 分钟前
差分进化算法深度解码:Scipy高效全局优化实战秘籍
python·算法·scipy
CSDN_RTKLIB25 分钟前
C++多元谓词
c++·算法·stl
LYS_061832 分钟前
寒假学习(2)(C语言2+模数电2)
c语言·学习·算法
listhi52043 分钟前
压缩感知信号重构的块稀疏贝叶斯学习(BSBL)算法:原理、实现与应用
学习·算法·重构
摸个小yu44 分钟前
【力扣LeetCode热题h100】哈希、双指针、滑动窗口
算法·leetcode·哈希算法
充值修改昵称1 小时前
数据结构基础:B+树如何优化数据库性能
数据结构·b树·python·算法
Cinema KI1 小时前
一键定位,哈希桶的极速魔法
数据结构·c++·算法·哈希算法