Solution to Problem 27 on Project Euler


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

The problem:

Euler discovered 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.

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.

My Solution

#include <stdio.h>

int isPrime(n){
  int i;
  if (n<=0)
    return 0;
  if (n==2)
    return 1;
  for (i=2;i<=n/2;i++)
    if(n%i==0)
      return 0;
  return 1;
}

int main(){
  int a,b,n,max,supermax,maxa,maxb;
  supermax=0;
  for (a=-999;a<1000;a++){
    for (b=-999;b<1000;b++){
      max=0;
      for (n=0;n<1000;n++){
        if(!isPrime((n*n)+(a*n)+b))
          break;
        max++;
      }
      if (max>supermax){
        supermax=max;
        maxa=a;
        maxb=b;
      }
    }
  }  
  printf("a = %d b = %d\n",maxa,maxb);      
return 0;
}

One thought on “Solution to Problem 27 on Project Euler

Leave a Reply

Your email address will not be published. Required fields are marked *