Python program to find number of digits in Nth Fibonacci number

In this tutorial, we will find the number of digits in the nth Fibonacci numbers in Python. First, we learn about Fibonacci numbers and then move on to the main program.

What are Fibonacci Numbers?

Starting from 0 and 1 other numbers are just the sum of the previous two numbers. For example, the third number of this series is 0+1=1, so the third number is 1. Similarly, the fourth number of this series will be 1+1=2, so the fourth number is 2.
Fibonacci Number Series : 0 1 1 2 3 5 8 13 21 and so on.
You can refer here to know more about Fibonacci Number
To check if a number is a Fibonacci number or not refer here.

Python Program

Here is our Python program for finding the number of digits of the nth Fibonacci series. About the program,

  • In this Python program, I have initialized two variables a, b as 0, 1 respectively. Next numbers are calculated with the help of for loop. This for loop runs (n-2) times as we have already initialized two numbers of this series earlier.
  • Inside the for loop, the next number is found by taking the sum of the previous two numbers and the result is stored in the variable containing the first number out of the two previous numbers. Then, both variables are swapped so that, variable a having the first number and variable b having the second number for finding the next number. This procedure will be repeated for (n-2) times so that we reach the nth number of our Fibonacci number series.
  • At last, to calculate the number of digits in our nth number of Fibonacci series, the number is converted to string type to apply the len() function and hence, find the length or number of digits of our number is calculated using the Python program.

Do try this program and see the results by yourself. I have added 3 outputs for your convenience.

a = 0
b = 1
n = int( input( 'Enter number: ' ) )

for i in range( n-2 ):
    a += b
    a,b = b,a
    
if( n == 1 ):
    print( 'Digit is: ', a )
else:
    print( 'Digit is: ', b )

print( 'Number of digits: ', len( str(b) ) )

Now its time to see outputs for different types of corresponding inputs given.

Output-1

Enter number: 4
Digit is:  2
Number of digits:  1

Output-2

Enter number: 10
Digit is: 34
Number of digits: 2

Output-3

Enter number: 100
Digit is: 218922995834555169026
Number of digits: 21

 

Leave a Reply

Your email address will not be published. Required fields are marked *