Skip to content

Instantly share code, notes, and snippets.

@nramirez
Last active August 29, 2015 14:14
Show Gist options
  • Save nramirez/f7729ff768657b85d60d to your computer and use it in GitHub Desktop.
Save nramirez/f7729ff768657b85d60d to your computer and use it in GitHub Desktop.
Sum of (Two) Squares
var allSquaredPairs = function(n){
var max = Math.sqrt(n),
posibles = [],
temp =0,
result = [],
i =0;
for(; i<=max; i++)
{
//Reference http://stackoverflow.com/questions/5380323/whats-the-fastest-algorithm-to-represent-a-prime-as-sum-of-two-squares
temp = Math.sqrt(n-i*i);
//If the sqrt(p-i^2) is an integer then is a part of the sqrt
if (temp %1 === 0) {
posibles.push(temp);
};
}
if(posibles.length == 1 )
{
//When it only contains one position the array is the following composition
result.push([posibles[0], posibles.pop()]);
}
while(posibles.length > 0)
{
result.push([posibles.shift(),posibles.pop()]);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment