メインコンテンツまでスキップ

How to check if a number is a Fibonacci number in Python

How to check if a number is a Fibonacci number in Python.

Here's a step-by-step tutorial on how to check if a number is a Fibonacci number in Python:

Step 1: Understand what Fibonacci numbers are​

Fibonacci numbers are a sequence of numbers in which each number is the sum of the two preceding ones. The sequence starts with 0 and 1. So, the Fibonacci sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.

Step 2: Prompt the user for a number to check​

To make the program interactive, we can ask the user to enter a number to check if it is a Fibonacci number.

number = int(input("Enter a number to check if it is a Fibonacci number: "))

Step 3: Check if the number is a perfect square​

One way to determine if a number is a Fibonacci number is to check if it is a perfect square. We can use the math.isqrt() function from the math module to calculate the square root of a number and check if it is an integer.

import math

def is_perfect_square(n):
return math.isqrt(n) ** 2 == n

Step 4: Check if the number or its adjacent numbers are Fibonacci numbers​

Since Fibonacci numbers are generated by adding the two previous numbers, we can iterate through the sequence until we find a number greater than or equal to the input number. If the number matches the input number, it is a Fibonacci number.

def is_fibonacci(n):
if is_perfect_square(5 * n * n + 4) or is_perfect_square(5 * n * n - 4):
return True
return False

Step 5: Test the function​

To verify the correctness of the implementation, we can test the function with some sample inputs.

numbers = [5, 8, 10, 13, 21, 25, 34, 55, 89]

for number in numbers:
if is_fibonacci(number):
print(number, "is a Fibonacci number")
else:
print(number, "is not a Fibonacci number")

Output:

5 is a Fibonacci number
8 is a Fibonacci number
10 is not a Fibonacci number
13 is a Fibonacci number
21 is a Fibonacci number
25 is not a Fibonacci number
34 is a Fibonacci number
55 is a Fibonacci number
89 is a Fibonacci number

That's it! You now have a Python program that can check if a number is a Fibonacci number.