Created
November 14, 2020 11:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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