Skip to content

Instantly share code, notes, and snippets.

@chaoxu
Created October 26, 2010 09:36
Show Gist options
  • Save chaoxu/646600 to your computer and use it in GitHub Desktop.
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.
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