Created
October 26, 2010 09:36
-
-
Save chaoxu/646600 to your computer and use it in GitHub Desktop.
Using Lagrange's four-square theorem and geometry to solve for square root.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SquareRoot { | |
public static double sqrt(int n){ | |
int[] v = vector(n); | |
return magnitude(v); | |
} | |
public static double magnitude(int[] v){ | |
double a=v[1],b=v[0]; | |
if(v.length>2){ | |
int[] u = new int[v.length-1]; | |
System.arraycopy(v, 1, u, 0, v.length-1); | |
a = magnitude(u); | |
} | |
b = v[0]; | |
return a/Math.sin(Math.atan(a/b)); | |
} | |
public static int[] vector(int n){ | |
int[] r = new int[4]; | |
for(r[0]=0;r[0]*r[0]<=n;r[0]++){ | |
for(r[1]=r[0];r[0]*r[0]+r[1]*r[1]<=n;r[1]++){ | |
for(r[2]=r[1];r[0]*r[0]+r[1]*r[1]+r[2]*r[2]<=n;r[2]++){ | |
for(r[3]=r[2];r[0]*r[0]+r[1]*r[1]+r[2]*r[2]+r[3]*r[3]<=n;r[3]++){ | |
if(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]+r[3]*r[3]==n){ | |
return r; | |
} | |
} | |
} | |
} | |
} | |
return new int[4]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment