Count Primes —— Leetcode

Description:

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

click to show more hints.

References:

How Many Primes Are There?

Sieve of Eratosthenes

参考References第二个链接,wikipedia上的动图,筛选算法,最后得出素数个数,算法如下:


注意int *array = new int[n]和int *array = new int[n]()的区别,前者不对数组初始化,后者初始化为0;

另外一个需要注意的地方是两个for循环的终止条件,不大于sqrt(n)和n;

我的源码如下:

class Solution {
public:
    int countPrimes(int n) {
        if(n<=2)
            return 0;
        int *array = new int[n]();
        int tmp, sum, count = n-2;
        for(int i=2; i<=(int) sqrt(n); i++)
        {
            if(!array[i])
            {
                tmp = i*i;
                for(int j=0; (sum=tmp+i*j)<n; j++)
                {
                    if(!array[sum])
                    {
                        array[sum] = true;
                        count--;
                    }
                }
            }
        }
        delete []array;
        
        return count;
    }
};

你可能感兴趣的:(Count Primes —— Leetcode)