Project Euler #27: Quadratic primes

Question
Euler discovered the remarkable quadratic formula:
It turns out that the formula will produce 40 primes for the consecutive integer values
. However, when is divisible by 41, and certainly when is clearly divisible by 41.
The incredible formula
was discovered, which produces 80 primes for the consecutive values . The product of the coefficients, −79 and 1601, is −126479.
Considering quadratics of the form:
, where and

where
is the modulus/absolute value of
e.g. and
Find the product of the coefficients,
and , for the quadratic expression that produces the maximum number of primes for consecutive values of , starting with .

Answer : -59231

Hacker Rank Problem

Solution


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.*;

public class Solution {

    //store the primes under 10000
    static boolean[] prime_array = new boolean[10000];

    static {
        for (int i = 2; i < 10000; i++) {
            if (isPrime(i)) {
                prime_array[i] = true;
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a0 = in.nextInt();
        int maxNumOfPrimes = 0;
        int resultA = 0;
        int resultB = 0;
        for (int a = -a0; a <= a0; a++) {
            for (int b = -a0; b <= a0; b++) {
                int count = 0;
                mainLoop: for (int n = 0;; n++) {
                    long r = n * n + a * n + b;
                    boolean re;
                    if (r < 0) {
                        break mainLoop;
                    }
                    if (r <= prime_array.length) {
                        re = prime_array[(int) r];
                    } else {
                        re = isPrime(r);
                    }
                    if (!re) {
                        break mainLoop;
                    }
                    count++;
                }
                if (count > maxNumOfPrimes) {
                    maxNumOfPrimes = count;
                    resultA = a;
                    resultB = b;
                }
            }
        }
        System.out.println(resultA + " " + resultB);
        in.close();
    }

    private static boolean isPrime(long r) {
        if (r < 2) {
            return false;
        }
        for (int i = 2; i * i <= r; i++) {
            if (r % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Comments

Popular Posts