Home > Software engineering >  I want to find if given numbers are in fibonacci sequence
I want to find if given numbers are in fibonacci sequence

Time:02-20

I want to find if the given numbers are in the Fibonacci sequence.

num = map(int,input("Enter numbers: ").split())

def fib(num):
    a = 0
    b = 1
    while b<num:
        c = a b
        a = b
        b = c
    if b==num or a==num:
        return True
    if b > num:
        return False

In this part I found the number if it's Fibonacci or not. But I couldn't find the sequence of fibonacci numbers.

CodePudding user response:

One way you can get the sequence is to store the result as you iterate through in a dictionary:

def in_fib(num):
    if num==0:
        return True
    d={}
    d[0]=0; d[1]=1
    i=2
    while d[i-1]<num:
        d[i]=d[i-1] d[i-2]
        i =1
    
    print("The sequence is: ", d.values())
    
    if d[i-1]==num:
        return True
    
    
    return False
    

print(in_fib(1))
print(in_fib(144))
print(in_fib(88))

Output:

'The sequence is: ', [0, 1])
True
('The sequence is: ', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144])
True
('The sequence is: ', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89])
False

CodePudding user response:

You need to shift the sum and last number to get to the next pair in the sequence:

def isFibo(N):
    a,b = 0,1
    while a<N:
        a,b = b,a b  # f(n) = f(n-1)   f(n-2)
    return a == N
  • Related