Chinaunix首页 | 论坛 | 博客
  • 博客访问: 216883
  • 博文数量: 68
  • 博客积分: 3120
  • 博客等级: 中校
  • 技术积分: 715
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-08 09:53
文章分类
文章存档

2012年(29)

2011年(3)

2010年(18)

2009年(18)

我的朋友

分类: C/C++

2012-01-18 20:25:14

问题:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.



答案:142913828922

#include
#include
#include

int isPrime(int n)
{
    if(1 == n) return 0;
    else if(4 > n ) return 1;
    else if(0 == (n%2)) return 0;
    else if(9 > n) return 1; //4, 6, 8 is excluded by row 7;
    else if(0 == (n%3)) return 0;
    else {
        int r = ( int)floor(sqrt((double)n));
        int f = 5;
        while(f <= r){
            if(0 == (n%f)) return 0;
            if(0 == (n%(f+2))) return 0;
            f += 6;
        }
        return 1;
    }
}


int main(void)
{
    const int limit = 2000000;
    double sum=5.0;
    int n = 5;
    while(n<=limit)
    {
        if(isPrime(n))
            sum += (double)n;
        n +=2;
        if(n<=limit && isPrime(n))
            sum += (double)n;
        n +=4;
    }
    printf("%f\n", sum);
    return 0;
}

/* The answer is 142913828922 */

阅读(664) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~