fork download
  1. #!/usr/bin/env python3
  2. def sicpfib(n):
  3. """Compute nth fibonacci number.
  4.  
  5. O(log(n)) steps, O(n) in memory (to hold the result)
  6.  
  7. Function Fib(count)
  8. a ← 1
  9. b ← 0
  10. p ← 0
  11. q ← 1
  12. While count > 0 Do
  13. If Even(count) Then
  14. p ← p² + q²
  15. q ← 2pq + q²
  16. count ← count ÷ 2
  17. Else
  18. a ← bq + aq + ap
  19. b ← bp + aq
  20. count ← count - 1
  21. End If
  22. End While
  23. Return b
  24. End Function
  25. See http://stackoverflow.com/questions/1525521/nth-fibonacci-number-in-sublinear-time/1526036#1526036
  26. """
  27. a, b, p, q = 1, 0, 0, 1
  28. while n > 0:
  29. if n % 2 == 0: # even
  30. oldp = p
  31. p = p*p + q*q
  32. q = 2*oldp*q + q*q
  33. n //= 2
  34. else:
  35. olda = a
  36. a = b*q + a*q + a*p
  37. b = b*p + olda*q
  38. n -= 1
  39. return b
  40.  
  41. print(*[sicpfib(i) for i in range(10)])
Success #stdin #stdout 0s 9992KB
stdin
Standard input is empty
stdout
0 1 1 2 3 5 8 13 21 34