Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. import math
  2.  
  3. def fib(n):
  4. ar = [0, 1]
  5. if n < len(ar):
  6. return ar[n]
  7. else:
  8. while n > len(ar)-1:
  9. ar.append(
  10. ar[len(ar)-1] + ar[len(ar)-2]
  11. )
  12. return ar[n]
  13.  
  14. def find_fib(sum):
  15. if sum < fib(500):
  16. n = 0
  17. while True:
  18. if fib(n) > sum:
  19. return -1 # This is an error code
  20. elif fib(n) < sum:
  21. n = n+1
  22. else:
  23. return n
  24. else:
  25. return find_fib_formula(sum)
  26.  
  27. # For sums greater than n=500 because the previous function will be too slow
  28. def find_fib_formula(sum):
  29. if sum <= fib(1000):
  30. Phi = (math.sqrt(5) + 1)/2
  31. formula_result = round(math.log((sum * math.sqrt(5)), Phi))
  32. if fib(formula_result) == sum:
  33. return formula_result
  34. else:
  35. return -1
  36. else:
  37. return find_big_fib(sum)
  38.  
  39. # For sums greater than n=1000 because Python can't handle the int->float conversion
  40. def find_big_fib(sum):
  41. Phi = (math.sqrt(5) + 1)/2
  42. possible_solution = round(math.log(sum * 2, Phi))
  43. if fib(possible_solution) == sum:
  44. return possible_solution
  45. else:
  46. possible_solutions = [
  47. possible_solution - 1,
  48. possible_solution - 2,
  49. possible_solution - 3,
  50. possible_solution + 1,
  51. possible_solution + 2,
  52. possible_solution + 3,
  53. ]
  54. for i in possible_solutions:
  55. if fib(i) == sum:
  56. return i
  57. return -1
  58.  
  59. #
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement