Getting the wrong answer for Project Euler # 27

I am working on Project Euler # 27 in C ++:

Euler posted a wonderful quadratic formula:

n² + n + 41

It turns out that the formula will give 40 primes for consecutive values ​​from n = 0 to 39. However, when n = 40, 40² + 40 + 41 = 40 (40 + 1) + 41 is divided by 41 and, of course, when n = 41, 41² + 41 + 41 is clearly divided by 41.

Using computers, the incredible formula n² - 79n + 1601 was that gives 80 primes for the following values ​​n = 0 to 79. The product of the coefficients -79 and 1601 is -126479.

Given the quadratic form:

n² + an + b, where |a| < 1000 and |b| < 1000 where |n| is the modulus/absolute value of n eg |11| = 11 and |−4| = 4 

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

I keep getting -60939 when the real answer is -59231. What am I missing?

 #include <iostream> #include "Helper.h" using namespace std; int formula(int a, int b, int n) { return ((n * n) + (a * n) + b); } int main() { int most = 0; int ansA = 0; int ansB = 0; bool end = false; for(int a = 999; a >= -999; a--) { for(int b = 999; b >= 2; b--) { //b must be prime if(Helper::isPrime(b)) { end = false; for(int n = 0; !end; n++) { if(!Helper::isPrime(formula(a, b, n))) { if(n-1 > most) { most = n-1; ansA = a; ansB = b; } end = true; } } } } } cout << ansA << " * " << ansB << " = " << ansA * ansB << " with " << most << " primes." << endl; return 0; } 

If this is a problem, here is my isPrime function:

 bool Helper::isPrime(int num) { if(num == 2) return true; if(num % 2 == 0 || num == 1 || num == 0) return false; int root = (int) sqrt((double)num) + 1; for(int i = root; i >= 2; i--) { if (num % i == 0) return false; } return true; } 
+4
source share
2 answers

You allow a be negative, and your formula returns int. Does calling Helper :: isPrime with a negative number even make sense (in other words, does Helper :: isPrime help an unsigned int?)

+4
source

Here is my version of java. Hope this helps:

 static int function(int n, int a, int b){ return n*n + a*n + b; } static int consequitive_Primes(int a, int b, HashSet<Integer> primes){ int n = 0; int number = 0; while(true){ if(!primes.contains(function(n, a, b))) break; number++; n++; } return number; } static HashSet<Integer> primes (int n){ ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(3); for(int i=3; i<n;i+=2){ boolean isPrime = true; for(Integer k:primes){ if(i%k==0){ isPrime = false; break; } } if(isPrime) primes.add(i); } return new HashSet<Integer>(primes); } static long q27(){ HashSet<Integer> primes = primes(1000); int max = 0; int max_ab = 0; for(int a = -999; a<1000;a++){ for(int b = -999; b<1000;b++){ int prime_No = consequitive_Primes(a,b,primes); if(max<prime_No){ max = prime_No; max_ab = a*b; } } } return max_ab; } 
0
source

All Articles