Skip to content

Instantly share code, notes, and snippets.

@angeloped
Last active June 4, 2020 19:50
Show Gist options
  • Save angeloped/51b333bb02abbbda0063ba365938fb06 to your computer and use it in GitHub Desktop.
Save angeloped/51b333bb02abbbda0063ba365938fb06 to your computer and use it in GitHub Desktop.
A simple Fibonacci sequence solver.
'''
written by: Bryan Angelo
'''
def fibCount(nth=0,ntp=0,sus=False): # where / limit / yield
# infinite loop
A,B = 1,1
nth_ = 0
while 1:
if bool(nth): # last number of specific iteration limit
if nth_ == nth:
yield B
elif bool(ntp): # return iteration count and nearest number reached
if B >= ntp:
yield (nth_, B)
elif bool(sus): # continuous computation
yield B
X = A + B
A = B
B = X
nth_ += 1
def isFibonacci(n):
# A utility function that returns true if x is perfect square
def isPerfectSquare(x):
s = None if x < 0 else x**0.5
# Returns true if n is a Fibinacci Number, else false
return s*s == x
# n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both is a perferct square
return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4)
if __name__ == "__main__":
import time
print(isFibonacci(5)) # determine if fibonacci number
time.sleep(1)
print(next(fibCount(nth=10))) # last number of specific iteration limit
time.sleep(1)
print(next(fibCount(ntp=10))) # return iteration count and nearest number reached
time.sleep(1)
for i in fibCount(sus=True): # continuous computation
print(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment