jueves, 9 de febrero de 2012

Project Euler 37

import java.util.BitSet;
import java.util.Scanner;
public class problem37{
 static BitSet a ;

 public static void main(String[] args){
  int c = 0;
  Scanner sc = new Scanner (System.in);

  int n = sc.nextInt(),
    i = 2,
    j = 0;

  a = new BitSet(n);

  for(i = 2 ; (i*i) <= n ; i = i+1)
   if(!a.get(i))
    for(j=i+i;j<=n;j=j+i)
     a.set(j);

  for(i=11;i<=n;i++)
   if(!a.get(i)){
    String aux = Integer.toString(i);
  
    if(check1(i)&&check2(i)&& aux.charAt(0)!='1'&&aux.charAt(aux.length()-1)!='1')
     c=c+i;
   
   }
  System.out.println(c);

 }

 public static boolean check1(int n){
  String num = Integer.toString(n);

  while(true) {

   num = num.replaceFirst("[0-9]","");

   if(num.equals(""))
    break;

   if(!a.get(Integer.parseInt(num)))
    continue;
   else
    return false;

  }
  return true;
 }

 public static boolean check2(int n) {
  String num = Integer.toString(n);

  while(true) {
   int leng =num.length();
   leng--;
   num = num.substring(0,leng );

   if(num.equals(""))
    break;

   if(!a.get(Integer.parseInt(num)))
    continue;
   else
    return false;

  }
  return true;
 }
}

No hay comentarios:

Publicar un comentario