leetCode刷题——Count Primes

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,const char * 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);

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值