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

2012年(29)

2011年(3)

2010年(18)

2009年(18)

我的朋友

分类: C/C++

2012-01-28 19:10:16

问题:

Euler published the remarkable quadratic formula:

n² + n + 41

It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41.

Using computers, the incredible formula  n² − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479.

Considering quadratics of the form:

n² + an + b, where |a| < 1000 and |b| < 1000

where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |−4| = 4

Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.


答案:-59231

#include
#include
#include
using namespace std;
bool 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(int argc, char *argv[])
{
   
    vector vec;

    for( int i=3; i<1000; i+=2 )
        if( isPrime(i) ) vec.push_back(i);

    int size = vec.size(), maxC = 0, result ;                   

    for( int a=-999; a<=999; a++ )
        for( int b=0; b            int c = 0;
            for( int n=0; n<100; n++ ){
                int pol = n*(a+n) + vec[b];
                if( pol > 0 ){
                    if( isPrime( pol ) )
                        c++;
                    else
                        break;
                }
                else
                    break;
            }
            if( c>maxC ){
                maxC = c;
                result = a*vec[b];
            }
        }

    printf("%d", result);
    return 0;
}

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