-1
x=int(input("Enter that number:"))
i=0
m=0
def fact(n):
    return 1 if(n==1 or  n==0) else  n+fact(n-1)
while(1):
    m=fact(i)
    if(m==x):
        print("Yes this is a Fib")
        break
    if(m>x):
        print("This is not a Fib")
        break
    i+=1

this is a code that is used to show if a number is in a fibniocci series or not can someone please tell me why this isnt working This shows not a fibonnicio series even if a number is of the series

zabop
  • 6,750
  • 3
  • 39
  • 84
  • 2
    Where did you get `n+fact(n-1)` from? That is not the right recursive relationship. Also, `fact` is a strange name for a Fibonacci function -- did you just take the Factorial recursive relationship and replace the multiplication with a sum? What you calculate here is a Triangular number. Finally, the name is not fibonnicio, nor fibniocci. It's Fibonacci. – trincot Dec 27 '20 at 15:02

4 Answers4

3

Mathematically, x is a Fibonacci number if and only if either 5x2 + 4 or 5x2 − 4 is a perfect square (Wikipedia). So the following algorithm tests if the input is a Fibonacci number without generating the whole sequence.

import math

def is_square(x):
    return math.isqrt(x)**2 == x

def is_fibonacci(x):
    return is_square(5 * x**2 + 4) or is_square(5 * x**2 - 4)

The math.isqrt function exists in Python 3.8 and later. If using an earlier version, see this Q&A.

kaya3
  • 47,440
  • 4
  • 68
  • 97
1

This solution generates fibonacci sequence elements until the input equals one of the elements or the maximum element of the series is bigger than the input.

def isFib(num):
    a = 0
    b = 1
    while (a <= num):
        if a == num:
            return True
        c = a+b
        a, b = b, c
    return False

The function can be used like this:

x = int(input("Enter a number: "))

if isFib(x):
    print("The number you entered is part of the fibonacci sequence")
else:
    print("The number you entered is not part of the fibonacci sequence")
Lcj
  • 371
  • 3
  • 10
0
x=int(input("Enter that number:"))
i=0
m=0
def fact(n):
    return n if (n == 1 or n == 0) else fact(n - 1)+fact(n-2)
while(1):
    m=fact(i)
    if(m==x):
        print("Yes this is a Fib")
        break
    if(m>x):
        print("This is not a Fib")
        break
    i+=1

You have made some mistake in recursive function this is correct function to find feb number.

Vashdev Heerani
  • 660
  • 7
  • 21
0

Yet another solution with generators for a more iterative look and feel, and the fibonacci function is now reusable..

from itertools import takewhile

def fibonacci_series():
    """ fibonacci generator"""
    n1, n2 = 0, 1
    yield n1
    yield n2
    while True:
        cur = n1 + n2
        yield cur
        n1, n2 = n2, cur

def is_fib(value):
    return value in takewhile(lambda x: x <= value, fibonacci_series())


if __name__ == '__main__':
    print(f'is_fib(10) : {is_fib(10)}')
    print(f'is_fib(55) : {is_fib(55)}')
    
Sam Daniel
  • 1,800
  • 12
  • 22