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;
}
相关推荐
槐月杰1 小时前
C语言中冒泡排序和快速排序的区别
c语言·算法·排序算法
笺上山河梦3 小时前
文件操作(二进制文件)
开发语言·c++·学习·算法
大慕慕好懒4 小时前
PHP弱类型hash比较缺陷
算法·哈希算法
snowfoootball4 小时前
最短路问题
数据结构·算法
有你的冬天1985 小时前
数据结构(一)
数据结构·算法
满怀10156 小时前
【Python进阶】列表:全面解析与实战指南
python·算法
爱学习的uu6 小时前
决策树:ID3,C4.5,CART树总结
算法·决策树·机器学习
wuqingshun3141596 小时前
蓝桥杯 9. 九宫幻方
数据结构·c++·算法·职场和发展·蓝桥杯·深度优先
小技与小术7 小时前
代码随想录算法训练营day4(链表)
数据结构·python·算法·链表
yasuniko7 小时前
C复习(主要复习)
c语言·数据结构·算法