sábado, 8 de enero de 2011

Project Euler

Me hacia falta subir los 3 problemas que les había mencionado en el post pasado.

Problema 3 dice:

  • The prime factors of 13195 are 5, 7, 13 and 29.What is the largest prime factor of the number 600851475143 ?
public static void problema3(){
  BigInteger bi= new BigInteger("600851475143");
  BigInteger resultado, ultimo;
  if(bi.mod(new BigInteger("2"))==(new BigInteger("0"))){
   bi=bi.divide(new BigInteger ("2"));
   while(bi.mod(new BigInteger("2"))==(new BigInteger("0")))
    bi=bi.divide(new BigInteger ("2"));
  }
  else
   resultado=new BigInteger("1");
  ultimo=new BigInteger("3");
  while(bi.compareTo(new BigInteger ("1"))==1){
   if(bi.mod(ultimo).intValue()==0){
    bi=bi.divide(ultimo);
    resultado=ultimo;
    while(bi.mod(ultimo)==new BigInteger ("0"))
     bi=bi.divide(ultimo);
   }
   ultimo=ultimo.add(new BigInteger("2"));
  }
  ultimo=ultimo.subtract(new BigInteger("2"));
  System.out.println("R3: "+ultimo);
 }
Problema 4 dice:
  • A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
    Find the largest palindrome made from the product of two 3-digit numbers.
public static void problema4(){
  Integer resultado=0;
  Integer resFin=0; 
  for(int i=999;i>=100; i--){
   for(int j=999;j>=100;j--){
    resultado=i*j;
    StringBuffer res=new StringBuffer(resultado+"");
    String res1=res.toString();
    String res2=(res.reverse()).toString();
    if(res1.equals(res2)){
     if(resultado >resFin)
      resFin=resultado;
    }
   }
  }
  System.out.println("R4: "+ resFin);
  
 }

Problema 5 dice:

  • 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
    What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
public static void problema5(){
  int i=20; 
  while ( (i % 20!=0)||(i % 19!=0)||(i % 18!=0)||(i % 17!=0)||(i % 16!=0)||(i % 15!=0)||(i % 14!=0)
    ||(i % 13!=0)||(i % 12!=0)||(i % 11!=0)||(i % 10!=0)||(i % 9!=0)||(i % 8!=0)||(i % 7!=0)
    ||(i % 6!=0)||(i % 5!=0)||(i % 4!=0)||(i % 3!=0)||(i % 2!=0)||(i % 1!=0)){ 
   i++; 
  } 
  System.out.println("R5: "+i); 
 } 


No hay comentarios:

Publicar un comentario