Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่าเลขเป็น Fibonacci Number หรือไม่ใน Python

โจทย์: กำหนดเลข n ตรวจสอบว่าเป็น Fibonacci number หรือไม่

คุณสมบัติ: n เป็น Fibonacci ถ้าและก็ต่อเมื่อ (5n² + 4) หรือ (5n² - 4) เป็น perfect square

โค้ดตัวอย่าง

import math

def isPerfectSquare(x):
    s = int(math.sqrt(x))
    return s*s == x

def isFibonacci(n):
    return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4)

for i in range(1, 11):
    if isFibonacci(i):
        print(i, "is a Fibonacci Number")
    else:
        print(i, "is not a Fibonacci Number")

ผลลัพธ์

1 is a Fibonacci Number
2 is a Fibonacci Number
3 is a Fibonacci Number
4 is not a Fibonacci Number
5 is a Fibonacci Number
6 is not a Fibonacci Number
7 is not a Fibonacci Number
8 is a Fibonacci Number
9 is not a Fibonacci Number
10 is not a Fibonacci Number

ตรวจสอบว่าเลขเป็น Fibonacci Number หรือไม่ใน Python

สรุป

เรียนรู้วิธีตรวจสอบ Fibonacci Number ใน Python: ใช้คุณสมบัติ 5n²±4 เป็น perfect square