Commit 2df37610 by Andrew Dahl

Solved Problem 27

parent a8894e8c
Showing with 70 additions and 0 deletions
Question:
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.
Answer: -59231
#include <iostream>
using namespace std;
const int MAX_A = 999;
const int MAX_B = 999;
bool is_prime(int num) {
if (num < 0)
return false;
for(int i = 2; i <= (num/2 + 1); i++) {
if((num % i) == 0) {
return false;
}
}
return true;
}
int find_consecutive_primes(int a, int b) {
int n = 0;
while(true) {
if(is_prime((n*n) + (n*a) + b))
n++;
else
break;
}
return n;
}
int main() {
int max_primes = 0;
int product = 0;
int temp = 0;
for(int a = (MAX_A * -1); a <= MAX_A; a++) {
for(int b = (MAX_B * -1); b <= MAX_B; b++) {
temp = find_consecutive_primes(a,b);
if(temp >= max_primes) {
max_primes = temp;
product = a * b;
}
}
}
cout << product << endl;
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment