leetCode刷题——Count Primes

来源:互联网 发布:mac登录界面英文 编辑:程序博客网 时间:2024/06/08 10:07

Description:

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

Hint: The number n could be in the order of 100,000 to 5,000,000.

题目觉得自己理解有误,理解的是在100,000到5,000,000里输出全部素数???

素数:约数只有1和自己。可以通过除数递增1的方式来寻找,但貌似遇到数据过多的情况,效率就显得低了。所以这里用到个更为优化的算法,引进sqrt()函数。

若n不是素数,则n可表示为a*b,其中2<=a<=b<=n-1,则a,b中必有一个数满足:1<x<=sqrt(n),因此,只需要用2~sqrt(n)去除n,这样就得到一个复杂度为O(sqrt(n))的算法。

以下是在Xcode上编译通过的C代码,但是在leetCode上报错(不排除题意理解错误):

 Output Limit Exceeded

#include <stdio.h>

#include <math.h>

int main(int argc,constchar * argv[]) 

{

   int x,y,num=0;

   for(x=100000;x<=5000000;x++)

    {

       for(y=2;y<=sqrt(x);y++)

           if(x%y==0)

               break;

       if(y>sqrt(x))

        {

           printf("%d\n",x);

            num++;

        }

    }

    printf("100000-5000000之间的素数有%d!\n",num);

}





0 0
原创粉丝点击