Program to find last two digits of Nth Fibonacci number in C++


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

Problem Description

We need to find the last two digits (i.e. the two LSB’s ) of the Nth Fibonacci number. Let’s take an example to understand the problem,

Input: N = 120 

Output: 81

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, we will use the property of the Fibonacci Series that last two digits repeats itself after 300 terms. I.e. The last two digits of the 75th term are the same as that of the 975th term.

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

Example

 Live Demo

#include <iostream>
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 findLastTwoDigitNterm(int N) {
   N = N % 300;
   return ( fibo(N)%100);
}
int main() {
   int N = 683;
   cout<<"The last two digits of "<<N<<"th Fibonacci term are "<<findLastTwoDigitNterm(N);
   return 0;
}

Output

The last two digits of 683th Fibonacci term are 97

Updated on: 09-Oct-2020

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements