Skip to content

Instantly share code, notes, and snippets.

@reuk
Created August 18, 2013 15:47
Show Gist options
  • Save reuk/6262308 to your computer and use it in GitHub Desktop.
Save reuk/6262308 to your computer and use it in GitHub Desktop.
More haskelling. This problem's nice - it's very easy to express recursively. It's easy to express iteratively too, of course. Actually, I find the iterative solution a lot clearer, which probably means my Haskell sucks. :(
//
// HASKELL
//
matches i (num, den) | i == 0 = 0
| g (num' + den') > g den' = 1 + f
| otherwise = f
where num' = den
den' = num + (2 * den)
f = matches (i - 1) (num', den')
g = length . show
solution = matches 1000 (1, 2)
main = print $ solution
//
// PYTHON
//
num = 1
den = 2
matches = 0
for i in xrange(1000):
num, den = den, (num + 2 * den)
if len(str(num + den)) > len(str(den)):
matches = matches + 1
print matches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment