Skip to content

Instantly share code, notes, and snippets.

@roychowdhuryrohit-dev
Created November 14, 2020 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roychowdhuryrohit-dev/e05f92af45a8df6d78afa16ab5853b72 to your computer and use it in GitHub Desktop.
Save roychowdhuryrohit-dev/e05f92af45a8df6d78afa16ab5853b72 to your computer and use it in GitHub Desktop.
Find all values in a list that are present in the following sequence : f(0) = 0, f(1) = 1, f(n) = 5*f(n-1) - 2*f(n-2) for all n > 1
from math import ceil, log, sqrt
"""
This solution uses the closed form expression of the given linear recurrence relation. Some approximations has been made to calculate the nearest value of n. Unlike other solutions that use recursion or memoization techniques, this is a much more faster and efficient constant time O(1) solution (assuming real-valued arithmetic is constant time).
"""
phi = 4.561552813
psi = 0.4384471872
sq = sqrt(17)
def isPresent(k):
if k == 0:
return True
sq = sqrt(17)
n = log(sq*k, phi)
m = ceil(n)
f_m = (phi**m - psi**m)//sq
return f_m == k
def is_part_of_series(lst):
res = []
for k in lst:
if isPresent(k):
res.append(k)
print(res)
# is_part_of_series([0,1,2,3,5,23,54,105,200,3000])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment