Check if a number is in the Fibonacci series

MediumIf-Else Programs · 8 of 64

Write a Python program to check whether a given number is part of the Fibonacci series (1, 1, 2, 3, 5, 8, 13, …).

Advertisement
Input
8, 10
Output
8 is a Fibonacci number
10 is not a Fibonacci number

Approach

  1. Generate Fibonacci numbers until they reach or pass the given number.
  2. If one of them equals the number, it is in the series.

Solution

Python
def is_fibonacci(n):    a, b = 0, 1    while a < n:        a, b = b, a + b    return a == n for n in [8, 10]:    print(n, "is a Fibonacci number" if is_fibonacci(n) else "is not a Fibonacci number")
Output
8 is a Fibonacci number
10 is not a Fibonacci number

Line by line

Lines 3-4

Keep stepping through the series while the current value is smaller than n.

Line 5

When the loop stops, a is either equal to n (found) or the first value past it (not found).

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs