fork download
  1. #!/usr/bin/env python3
  2. import decimal
  3. import math
  4.  
  5. from functools import lru_cache
  6. from itertools import islice
  7. from collections import deque
  8.  
  9. limit = 4000000
  10. s = 0
  11. a, b = 0, 2
  12. while a < limit:
  13. s += a
  14. a, b = b, 4 * b + a
  15. print(s)
  16.  
  17. # http://m...content-available-to-author-only...e.com/questions/323058/closed-form-for-the-sum-of-even-fibonacci-numbers
  18. @lru_cache(maxsize=4)
  19. def G(n):
  20. if n == 0: return 0
  21. elif n == 1: return 2
  22. elif n == 2: return 8
  23. else: return 5 * G(n-1) - 3 * G(n-2) - G(n-3)
  24.  
  25. print(sum(e for e in map(G, range(20)) if e < limit))
  26.  
  27. s = 0
  28. a, b, c = 0, 2, 8
  29. while a < limit:
  30. s += a
  31. a, b, c = b, c, 5*c - 3*b - a
  32. print(s)
  33.  
  34. def fib(a=0, b=1):
  35. while True:
  36. yield a
  37. a, b = b, a+b
  38.  
  39. # (F[3*n+2]-1) // 2
  40. n = 11
  41. print((deque(islice(fib(), 3*(n+1)), maxlen=1)[0] - 1) // 2)
  42.  
  43. def binet_decimal(n, precision):
  44. """Calculate nth fibonacci number using Binet's formula."""
  45. with decimal.localcontext() as cxt:
  46. cxt.prec = precision
  47. with decimal.localcontext(cxt) as nested_cxt:
  48. nested_cxt.prec += 2 # increase prec. for intermediate results
  49. sqrt5 = decimal.Decimal(5).sqrt()
  50. f = ((1 + sqrt5) / 2)**n / sqrt5
  51. return +f.to_integral() # round to required precision
  52.  
  53. def ndigits_fibn(n):
  54. """Find number of decimal digits in fib(n)."""
  55. phi = (1 + math.sqrt(5)) / 2
  56. return int(n*math.log10(phi)-math.log10(5)/2)+1
  57.  
  58. def binetfib_exact(n):
  59. return binet_decimal(n, ndigits_fibn(n))
  60.  
  61. print((binetfib_exact(3*n+2) - 1) // 2)
Success #stdin #stdout 0.02s 11656KB
stdin
Standard input is empty
stdout
4613732
4613732
4613732
4613732
4613732