Facebook Hacker Cup - Double Squares Problem - In Coffee!
Publishing a coding challenge just for fun. Yup, this is what I do for fun first thing in the morning. I hear one guy did this in 38 characters of Perl.
The challenge is to write a script that will determine how many ways N can be written as the sum of the squares of two nonzero positive integers where N is also a nonzero positive integer. Checking your work, the result for 25 should be 1, 338 should be 2 and 1000000 should be 3. Extra credit for making the algorithm as efficient as possible.
# define function
this.doubleSquareFinder = (number) ->
combinations = 0
# memoize for speed
doubleSquareFinder.hash = doubleSquareFinder.hash || {}
if typeof doubleSquareFinder.hash[number] != 'undefined'
return doubleSquareFinder.hash[number]
#no need to check numbers larger than what is possible
range = Math.sqrt number/2
half = number/2
# iterate
for a in [1..range]
for b in [a..half]
combinations++ if (a*a + b*b == number)
doubleSquareFinder.hash[number] = combinations
return combinations