leetcode count pirmes

来源:互联网 发布:与知否一样好看的小说 编辑:程序博客网 时间:2024/06/15 06:17

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

传统方法会出现TLC,转载一个埃拉托斯特尼筛法Sieve of Eratosthenes,这个算法的过程如下,我们从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,依此类推,直到根号n,此时数组中未被标记的数字就是质数。

代码如下:

public int countPrimes(int n) {   int[] res=new int[n];    int k=(int)Math.sqrt(n);    int count=0;    for(int i=2;i<=k;i++)    {        if(isPrime(i))        {            for(int j=i*i;j<n;j+=i)            {                res[j-1]=1;            }        }    }    for(int i=1;i<res.length;i++)    {        if(res[i]==0)            count++;    }    return count;}public  boolean isPrime(int num){    int k=(int)Math.sqrt(num);    for(int i=2;i<=k;i++)    {        if(num%i==0)            return false;    }    return true;}

    0 0
    原创粉丝点击