Pages

Thursday, August 18, 2011

Lagrange's four-square theorem implementation code in JAVA

Lagrange's four-square theorem : any natural number can be represented as the sum of four integer squares

p = a02 + a12 + a22 + a32

where the four numbers a0, a1, a2, a3 are integers. For illustration, 3, 31 and 310 can be represented as the sum of four squares as follows:

3 = 12 + 12 + 12 + 02
31 = 52 + 22 + 12 + 12
310 = 172 + 42 + 22 + 12.

 int n, t1, t2, t;  
           n = 23;//Your number  
           for (int i = (int) Math.sqrt(n / 4); i * i <= n; i++) {  
                t1 = n - i * i;  
                for (int j = (int) Math.sqrt(t1 / 3); j <= i && j * j <= t1; j++) {  
                     t2 = t1 - j * j;  
                     for (int k = (int) Math.sqrt(t2 / 2); k <= j && k * k <= t2; k++) {  
                          t = (int) Math.sqrt(t2 - k * k);  
                          if (t <= k && t * t == t2 - k * k) {                                
                               System.out.println("(" + i + "^2) + (" + j + "^2) + ("+ k + "^2) + ("+ t +"^2)");  
                          }  
                     }  
                }  
           }  


No comments:

Post a Comment