zoukankan      html  css  js  c++  java
  • Project Euler Problem 27 Quadratic primes

    Quadratic primes

    Problem 27

    Euler discovered the remarkable quadratic formula:

    n2+n+41

    It turns out that the formula will produce 40 primes for the consecutive integer values 0n39

    . However, when n=40,402+40+41=40(40+1)+41 is divisible by 41, and certainly when n=41,412+41+41

    is clearly divisible by 41.

    The incredible formula n279n+1601

    was discovered, which produces 80 primes for the consecutive values 0n79

    . The product of the coefficients, −79 and 1601, is −126479.

    Considering quadratics of the form:

    n2+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.


    C++:

    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    const int N = 1000;
    
    bool isprime(int n)
    {
        if(n == 1)
            return false;
    
        if(n == 2)
            return true;
    
        if(n % 2 == 0)
            return false;
    
        int end = sqrt(n);
        for(long i=3; i<=end; i+=2)
            if(n % i == 0)
                return false;
    
        return true;
    }
    
    int main()
    {
        int ans, maxn=0, n, expr;
    
        for(int b=1; b<N; b++)
            if(isprime(b)) {
                for(int a=-b; a<N; a++) {
                    n = 0;
                    expr = n * n + a * n + b;
                    while(expr > 0 && isprime(expr)) {
                        n++;
                        expr = n * n + a * n + b;
                    }
    
                    if(n > maxn) {
                        maxn = n;
                        ans = a * b;
                    }
                }
            }
    
        cout << ans << endl;
    
        return 0;
    }



  • 相关阅读:
    iOS序列化与反序列化
    iOS官方文档阅读 基本格式指北
    iOS实现地图半翻页效果--老代码备用参考
    AVQueuePlayer
    ios音频视频资料--备用
    ios coredata 老代码备用参考
    uitableviewcell 自适应大小 参考
    触发UIButton长按事件
    gsoap 学习 1-由wsdl文件生成h头文件
    gsoap简介
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7563989.html
Copyright © 2011-2022 走看看