Program to find last digit of n’th Fibonnaci Number in C++


In this problem, we are given a number N. Our task is to create a Program to find last digit of Nth Fibonacci number in C++.

Problem Description

We need to find the last digit (i.e. LSB ) of the Nth Fibonacci number.

Let’s take an example to understand the problem,

Input: N = 120 Output: 1

Solution Approach

A simple solution will be using the direct Fibonacci formula to find the Nth term. But this method will not be feasible when N is a large number. So to overcome this thing, we will use the property of the Fibonacci Series that the last digit repeats itself after 60 terms. I.e. The last digit of the 75th term is the same as that of the 135th term.

This means that working till 60 will give us all possible combinations and to find which term to use we will find the number’s mod with 60.

Example

 Live Demo

#include
using namespace std;
long int fibo(int N){
   long int a=0,b=1,c;
   for(int i=2; i< N;i++) {
      c=a+b;
      a=b;
      b=c;
   }
   return c;
}
int findLastDigitNterm(int N) {
   N = N % 60;
   return ( fibo(N)%10);
}
int main() {
   int N = 683;
   cout<<"The last digit of "<<N<<"th Fibonacci term is "<<findLastDigitNterm(N);
   return 0;
}

Output

The last digit of 683th Fibonacci term is 1

Updated on: 09-Oct-2020

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements