204. Count Primes

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

**思路:**这道题可以考虑用打表的方式来解,但考虑到n值会很大,用数组存储会爆的,所以考虑用指针来保存。

int countPrimes(int n) {
    int *isPrime=(int *)malloc(n*sizeof(int));
    memset(isPrime,0,sizeof(isPrime));
    for(int i=2;i*i<n;i++)
    {
        if(isPrime[i]) continue;
        for(int j=i*i;j<n;j+=i)
        {
            isPrime[j]=1;
        }
    }
    int count=0;
    for(int i=2;i<n;i++)
    {
        if(!isPrime[i]) count++;
    }
    return count;
}

LeetCode 204 计数质数

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2021-06-08
  • 2021-10-20
  • 2021-12-04
  • 2021-12-08
猜你喜欢
  • 2021-07-15
  • 2022-02-11
  • 2021-05-19
  • 2021-09-06
  • 2021-07-28
  • 2021-05-20
  • 2021-06-11
相关资源
相似解决方案