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<=5106

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:
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. <span style='color:red;'>2014</span>

    2014

    2024-07-10 19:56:01      41 阅读
  2. 2024.1.20

    2024-07-10 19:56:01       59 阅读
  3. 2024/2/20

    2024-07-10 19:56:01       39 阅读
  4. 2024/4/24总结

    2024-07-10 19:56:01       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 19:56:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 19:56:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 19:56:01       58 阅读
  4. Python语言-面向对象

    2024-07-10 19:56:01       69 阅读

热门阅读

  1. 【debug】keras使用基础问题

    2024-07-10 19:56:01       18 阅读
  2. Qt 绘图详解

    2024-07-10 19:56:01       23 阅读
  3. MySQL篇七:复合查询

    2024-07-10 19:56:01       26 阅读
  4. [GDOUCTF 2023]Tea writeup

    2024-07-10 19:56:01       27 阅读
  5. 软件开发C#(Sharp)总结(续)

    2024-07-10 19:56:01       17 阅读
  6. CSS 样式链接的多方面应用与最佳实践

    2024-07-10 19:56:01       22 阅读
  7. 西门子7MB2335-0AL00-3AA1

    2024-07-10 19:56:01       19 阅读