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;
}
相关推荐
syt_biancheng24 分钟前
Day3算法训练(简写单词,dd爱框框,3-除2!)
开发语言·c++·算法·贪心算法
二进制的Liao39 分钟前
【编程】脚本编写入门:从零到一的自动化之旅
数据库·python·算法·自动化·bash
自然数e1 小时前
C++多线程【线程管控】之线程转移以及线程数量和ID
开发语言·c++·算法·多线程
云在Steven2 小时前
在线确定性算法与自适应启发式在虚拟机动态整合中的竞争分析与性能优化
人工智能·算法·性能优化
2401_861277552 小时前
软考程序员2016年上半年二叉排序树案例题解答
c语言·决策树·链表
前进的李工2 小时前
LeetCode hot100:234 回文链表:快慢指针巧判回文链表
python·算法·leetcode·链表·快慢指针·回文链表
sin_hielo2 小时前
leetcode 3228
算法·leetcode
xier_ran3 小时前
力扣(LeetCode)100题:41.缺失的第一个正数
数据结构·算法·leetcode
Swift社区4 小时前
LeetCode 425 - 单词方块
算法·leetcode·职场和发展
weixin_307779134 小时前
软件演示环境动态扩展与成本优化:基于目标跟踪与计划扩展的AWS Auto Scaling策略
算法·云原生·云计算·aws