Advertisement
doanhtu

Project Euler #25

Mar 6th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. di = {}  # Memoize
  2.  
  3.  
  4. def fib(n):
  5.     if n <= 2:
  6.         return 1
  7.     else:
  8.         if di.get(n):
  9.             return di[n]
  10.         else:
  11.             result = fib(n - 1) + fib(n - 2)
  12.             di[n] = result
  13.             return result
  14.  
  15. ################################################
  16. # Or you can use existing function: lru_cache ##
  17. ################################################
  18.  
  19. # from functools import lru_cache
  20. # @lru_cache(maxsize=None)
  21. # def fib(n):
  22. #     if n <= 2:
  23. #         return n
  24. #     return fib(n - 1) + fib(n - 2)
  25.  
  26. def main():
  27.     i = 0
  28.     while True:
  29.         i += 1
  30.         if len(str(fib(i))) == 1000:
  31.             return i
  32.  
  33.  
  34. if __name__ == '__main__':
  35.     main()
  36.  
  37.  
  38. In [35]: %time main()
  39. CPU times: user 45.9 ms, sys: 63 ยตs, total: 45.9 ms
  40. Wall time: 45.1 ms
  41. Out[35]: 4782
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement