Last active
December 19, 2015 17:09
-
-
Save scturtle/5989270 to your computer and use it in GitHub Desktop.
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
| fib' 1 = (0, 1, 1) | |
| fib' n = let (a, b, c) = fib' (n `div` 2) | |
| a' = a*a + b*b | |
| b' = a*b + b*c | |
| c' = b*b + c*c | |
| in if n `rem` 2 == 1 then (b', c', b' + c') | |
| else (a', b', c') | |
| fib 0 = 0 | |
| fib n = let (_, v, _) = fib' n in v |
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
| def fib(n, memo={1: (0, 1, 1)}): | |
| if n in memo: | |
| return memo[n] | |
| a, b, c = fib(n/2) | |
| a, b, c = a*a+b*b, a*b+b*c, b*b+c*c | |
| if n & 1: | |
| a, b, c = b, c, b+c | |
| memo[n] = a, b, c | |
| return memo[n] |
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
| def fib(n, memo={0: (0, 1)}): | |
| if n not in memo: | |
| a, b = fib(n // 2) | |
| c = a * (2 * b - a) | |
| d = a * a + b * b | |
| memo[n] = (d, c + d) if n & 1 else (c, d) | |
| return memo[n] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment