Sunday, February 25, 2024

BCA PART A 1. Check if a number belongs to the Fibonacci Sequence

 A Fibonacci number is a member of the Fibonacci sequence, a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence begins:

0,1,1,2,3,5,8,13,21,34,

Starting with 0 and 1, each subsequent Fibonacci number is obtained by adding the two numbers that precede it. Mathematically, it can be defined by the recurrence relation:

()=(1)+(2)

with initial conditions (0)=0 and (1)=1.

The Fibonacci sequence has many interesting mathematical properties and applications, and it often appears in various areas of mathematics and nature, including the arrangement of leaves on a stem, the branching of trees, and the arrangement of seeds in a sunflower.

Program :

def is_perfect_square(n):
# Helper function to check if a number is a perfect square
root = int(n**0.5)
return n == root * root

def is_fibonacci_number(number):
# A number 'n' is a Fibonacci number if and only if one of
#(5 * n^2 + 4) or # (5 * n^2 - 4) is a perfect square
return is_perfect_square(5 * number**2 + 4) or
is_perfect_square(5 * number**2 - 4)

# Get user input
user_input = int(input("Enter a number to check if it belongs
to the Fibonacci sequence: "))

# Check if the number belongs to the Fibonacci sequence
if is_fibonacci_number(user_input):
print(f"{user_input} is a Fibonacci number.")
else:
print(f"{user_input} is not a Fibonacci number.")

  1. is_perfect_square(n) Function:

    • This function is a helper function that takes a number n as input and checks if it is a perfect square.
    • It calculates the square root of n using the exponentiation (**) operator.
    • It then checks if the square of the calculated root is equal to the original number n. If it is, then the number is a perfect square.
  2. is_fibonacci_number(number) Function:

    • This function takes a number number as input and determines whether it belongs to the Fibonacci sequence.
    • It checks if either (5 * number^2 + 4) or (5 * number^2 - 4) is a perfect square using the is_perfect_square function.
    • If either of these expressions results in a perfect square, the input number is considered part of the Fibonacci sequence.
  3. User Input:

    • The program prompts the user to enter a number using input().
    • The entered number is converted to an integer using int().
  4. Checking and Output:

    • The program then calls the is_fibonacci_number function with the user-entered number.
    • If the number is determined to be a Fibonacci number, the program prints that the number is a Fibonacci number. Otherwise, it prints that the number is not a Fibonacci number.

For example, if the user enters 5, the program will output that 5 is a Fibonacci number, because 5 is part of the Fibonacci sequence (0, 1, 1, 2, 3, 5, ...).


No comments:

Post a Comment