Project Euler #167: Investigating Ulam sequences

  • + 0 comments

    public class Solution {

    public static void main(String[] args) {
    Scanner in = new Scanner(System.in); 
     try{
    
     int n = in.nextInt(); 
     int k = in.nextInt(); 
    
     int array[] = new int[k+1]; 
    
        array[0]=2; 
       array[1]=2*n+1; 
        List<Integer> list2 = new ArrayList<Integer>();
       for(int i = 2; i<k; i++){
            List<Integer> list = new ArrayList<Integer>();
    
           for(int j = 0; j<i-1; j++){
               for(int kk=j+1; kk<i; kk++){
                   int a = array[j]+array[kk]; 
                   if(a>array[i-1]){list.add(a);}; 
               }
           }
          Collections.sort(list);
                // System.out.println("list 1"+ list );
          Set<Integer> set = new HashSet<Integer>(list);
    
      for(Integer tmp:set)
         {       
          if(Collections.frequency(list, tmp)==1){
                    list2.add(tmp);       
          }
    }
    
         Collections.sort(list2); 
           array[i]=list2.get(0); 
          //System.out.println("list 1" +list2 );
           list2.clear(); 
       }
      System.out.println(array[k-1] );
    
    
    
    }catch(Exception e){
        System.out.println("Error"); 
    }
    }      
    

    }