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;
}
相关推荐
zhangfeng113319 分钟前
大语言模型 bpe算法 后面对接的是 one-hot吗 nn.Embedding
算法·语言模型·embedding
Pluchon22 分钟前
硅基计划4.0 算法 动态规划高阶
java·数据结构·算法·leetcode·深度优先·动态规划
人间不清醒ab22 分钟前
FREERTOS检测任务栈内存情况
c语言·单片机
科学计算技术爱好者29 分钟前
NVIDIA GPU 系列用途分类梳理
人工智能·算法·gpu算力
程序员敲代码吗29 分钟前
嵌入式C++开发注意事项
开发语言·c++·算法
好学且牛逼的马30 分钟前
【Hot100|14-LeetCode53. 最大子数组和】
数据结构·算法·leetcode
无心水33 分钟前
17、Go协程通关秘籍:主协程等待+多协程顺序执行实战解析
开发语言·前端·后端·算法·golang·go·2025博客之星评选投票
东华果汁哥1 小时前
【机器视觉 行人检测算法】FastAPI 部署 YOLO 11行人检测 API 服务教程
算法·yolo·fastapi
每天学一点儿1 小时前
[SimpleITK] 教程 63:配准初始化 (Registration Initialization) —— 从几何对齐到手动干预。
算法
君义_noip1 小时前
信息学奥赛一本通 1463:门票
c++·算法·哈希算法·信息学奥赛·csp-s