Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- def fib(n):
- ar = [0, 1]
- if n < len(ar):
- return ar[n]
- else:
- while n > len(ar)-1:
- ar.append(
- ar[len(ar)-1] + ar[len(ar)-2]
- )
- return ar[n]
- def find_fib(sum):
- if sum < fib(500):
- n = 0
- while True:
- if fib(n) > sum:
- return -1 # This is an error code
- elif fib(n) < sum:
- n = n+1
- else:
- return n
- else:
- return find_fib_formula(sum)
- # For sums greater than n=500 because the previous function will be too slow
- def find_fib_formula(sum):
- if sum <= fib(1000):
- Phi = (math.sqrt(5) + 1)/2
- formula_result = round(math.log((sum * math.sqrt(5)), Phi))
- if fib(formula_result) == sum:
- return formula_result
- else:
- return -1
- else:
- return find_big_fib(sum)
- # For sums greater than n=1000 because Python can't handle the int->float conversion
- def find_big_fib(sum):
- Phi = (math.sqrt(5) + 1)/2
- possible_solution = round(math.log(sum * 2, Phi))
- if fib(possible_solution) == sum:
- return possible_solution
- else:
- possible_solutions = [
- possible_solution - 1,
- possible_solution - 2,
- possible_solution - 3,
- possible_solution + 1,
- possible_solution + 2,
- possible_solution + 3,
- ]
- for i in possible_solutions:
- if fib(i) == sum:
- return i
- return -1
- #
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement