Project Euler #229: Four Representations using Squares

  • + 0 comments

    static LinkedHashMap counts = new

    LinkedHashMap();

    public static void FourRepresentation(long x) {
    
    
        // i^2 + j^2
        for (long i = 1; i <= (int) Math.sqrt(x); i++) {
            for (long j = 1; j <= (int) Math.sqrt(x); j++) {
    
                if (i * i + 7 * j * j < x  && i * i + 7 * j * j >190 ) {
                    counts.put(i * i + 7 * j * j, 1);
                }
    
            }
        }
    
    
        loop:
        for(long i=1;i<= (int)Math.sqrt(x) ;i++){
        for(long j=1;j<=(int)Math.sqrt(x); j++){
    
        if(counts.containsKey(i*i +  j *j) && counts.get(i*i + j *j) == 1){
        counts.put( (i*i + j*j), counts.get(i*i +  j*j)+1);
        }
        }
        }
    
        loop2:
        for(long i=1;i<= (int)Math.sqrt(x) ;i++){
        for(long j=1;j<= (int)Math.sqrt(x) ; j++){
        if(counts.containsKey(i*i + 3 * j *j) && counts.get(i*i + 3 * j *j) == 2 ){
        counts.put( (i*i + 3 * j*j), counts.get(i*i + 3 * j*j)+1);
    
        }
        }
        }
    
        loop1:
        for(long i=1;i<= (int)Math.sqrt(x) ;i++){
        for(long j=1;j<=(int)Math.sqrt(x) ; j++){
    
        if(counts.containsKey(i*i + 2 * j *j) && counts.get(i*i + 2 * j *j) == 3 ){
        counts.put( (i*i + 2 * j*j),counts.get(i*i + 2* j*j)+1);
    
        }
    
        }
        }
    
    
    
                **How to optimize this ! thanks**
    
    
        System.out.println(Collections.frequency(counts.values(), 4));
    
    1. }