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;
}
相关推荐
茉莉玫瑰花茶6 分钟前
C++ 17 详细特性解析(4)
开发语言·c++·算法
mancy_1212129 分钟前
复古C语言代码复活!——以121+hello.c为例摘要
c语言·vscode·gitee·visual studio·新人首发·turbo c
long31621 分钟前
K‘ 未排序数组中的最小/最大元素 |期望线性时间
java·算法·排序算法·springboot·sorting algorithm
进击的小头24 分钟前
FIR滤波器实战:音频信号降噪
c语言·python·算法·音视频
xqqxqxxq28 分钟前
洛谷算法1-1 模拟与高精度(NOIP经典真题解析)java(持续更新)
java·开发语言·算法
razelan28 分钟前
初级算法技巧 4
算法
砍树+c+v29 分钟前
3a 感知机训练过程示例(手算拆解,代码实现)
人工智能·算法·机器学习
zy_destiny30 分钟前
【工业场景】用YOLOv26实现4种输电线隐患检测
人工智能·深度学习·算法·yolo·机器学习·计算机视觉·输电线隐患识别
智驱力人工智能40 分钟前
货车违规变道检测 高速公路安全治理的工程实践 货车变道检测 高速公路货车违规变道抓拍系统 城市快速路货车压实线识别方案
人工智能·opencv·算法·安全·yolo·目标检测·边缘计算
罗湖老棍子44 分钟前
【例9.18】合并石子(信息学奥赛一本通- P1274)从暴搜到区间 DP:石子合并的四种写法
算法·动态规划·区间dp·区间动态规划