Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check input that belong to Fibonacci numbers in Python

Tags:

python

I would like to ask how can I retrieve out the list of fibo list and then check whether does the input value by the user is inside the fibo list.

    a , b = 1, 1
while num <= sys.maxint:
    fibo == a , b = b, a+b
    if num == (b +a+b):
        print "It is a Fibonacci number"        
        break
    else:
        print "It is not a Fibonacci number"
        break

Thank you!

like image 627
user950472 Avatar asked Sep 19 '11 13:09

user950472


People also ask

How do you check if a number belongs to Fibonacci?

A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki).

How do you know if an object has Fibonacci?

Seed heads, pinecones, fruits and vegetables: Look at the array of seeds in the center of a sunflower and you'll notice what looks like spiral patterns curving left and right. Amazingly, if you count these spirals, your total will be a Fibonacci number.

How do you find the nth term of a Fibonacci sequence in Python?

Practical Data Science using Python We have to find the nth Fibonacci term by defining a recursive function. So, if the input is like n = 8, then the output will be 13 as first few Fibonacci terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... otherwise, return solve(n - 1) + solve(n - 2)


2 Answers

Using a more sophisticated Fibonacci number test, you could use

def is_fibonacci(n):
    phi = 0.5 + 0.5 * math.sqrt(5.0)
    a = phi * n
    return n == 0 or abs(round(a) - a) < 1.0 / n

(This is probably the most efficient way to determine whether a number is a Fibonacci number, and it is most probably not the intended solution to your homework. I just included this answer for future reference.)

like image 79
Sven Marnach Avatar answered Nov 09 '22 10:11

Sven Marnach


A pythonic one-liner

def is_fibonacci(n):
    return n >= 0 and (n==0 or sqrt( 5*n*n - 4).is_integer() or sqrt( 5*n*n + 4).is_integer())
like image 40
hoke1606 Avatar answered Nov 09 '22 11:11

hoke1606