
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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