jueves, 9 de febrero de 2012

Project Euler 27

public class Problem27 {
 static boolean[] criba;
 public static void main(String[] args) {
  generarCriba(10000000);
  int a=0,b=0,n=0,max = 0;
  long producto=0;
  try{
  for(a = -1000 ; a<=1000;a++)
   for(b = -1000 ; b<=1000;b++){
    int c = 0;
    for(n = 0 ; ;n++){
     int f = fun(n,a,b);
     if(!criba[f])
      c++;
     else
      break;
    }
    if(c>max){
     max = c;
     producto = a*b;
    }
     
   }
  }catch (Exception e) {
   System.out.println("Fallo en :");
   System.out.println(a+"  "+b+"  "+n);
   return;
  }
  System.out.println(producto);   
 }
 public static int fun(int n, int a,int b){
  return Math.abs(n*n+a*n+b);
 }
 public static void generarCriba(int n){
  criba = new boolean[n+1];
  criba[0] = criba[1] = true;
  for (int i = 2; i*i <= n; i++) 
   if(!criba[i])
   for (int j = i+i; j <= n; j+=i) 
    criba[j] = true;
 }
}

No hay comentarios:

Publicar un comentario