Project Euler #167: Investigating Ulam sequences

  • + 1 comment

    import java.util.; import java.text.; import java.math.; import java.util.regex.;

    public class Solution {

    public static void main(String[] args) {
    Scanner in = new Scanner(System.in); 
     int n = in.nextInt(); 
     int k = in.nextInt(); 
    
     int array[] = new int[k+2]; 
       array[0]=n; 
       array[1]=2*n+1; 
    
        if(k>2){
    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);
          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); 
    
           list2.clear(); 
       }
        }
      System.out.println(array[k-1] );
    
    }}