Last active
August 29, 2015 14:14
-
-
Save nramirez/f7729ff768657b85d60d to your computer and use it in GitHub Desktop.
Sum of (Two) Squares
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
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