VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-find-last-two-digits-nth-fibonacci-number/

⇱ Program to find last two digits of Nth Fibonacci number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find last two digits of Nth Fibonacci number

Last Updated : 24 Mar, 2023

Given a number ā€˜n’, write a function that prints the last two digits of n-th (ā€˜n’ can also be a large number) Fibonacci number.
Examples: 

Input : n = 65
Output : 65

Input : n = 365
Output : 65

Recommended: Please solve it on ā€œā€ first, before moving on to the solution.

A simple solution is to find n-th Fibonacci number and print its last two digit. But N can be very large, so it wouldn't work. 
A better solution is to use the fact that after 300-th Fibonacci number last two digits starts repeating. 
1) Find m = n % 300. 
2) Return m-th Fibonacci number. 
 

Output:  

1
61
13
53

Time Complexity: O(300), it will run in constant time.
Auxiliary Space: O(300), no extra space is required, so it is a constant.

Approach 2: Iterative Approach:

In this implementation, we simply iterate through the Fibonacci sequence up to the n-th number, keeping track of the last two digits of each number using the modulo operator. This allows us to compute the last two digits of even large Fibonacci numbers without needing to store all of the previous numbers in the sequence.

Here Are steps of this approach:

  • We start by initializing the first two terms of the sequence to 0 and 1 respectively. Then, for each i from 2 to n, we calculate the ith Fibonacci number by adding the (i-1)th and (i-2)th Fibonacci numbers.
  • In each iteration, we keep track of the previous two Fibonacci numbers using two variables, prev and curr. Initially, prev is set to 0 and curr is set to 1. In each iteration, we update prev to curr and curr to the sum of prev and curr. After n iterations, the value of curr is the nth Fibonacci number.
  • This approach has a time complexity of O(n) and a space complexity of O(1) since we only need to store two variables at any given time. This makes it more efficient than the recursive approach, which has a time complexity of O(2^n) and a space complexity of O(n). However, the iterative approach can be harder to understand than the recursive approach for some people, as it involves more explicit manipulation of variables and requires a good understanding of loops and basic arithmetic operations.

Output
1
61
13
53

Time Complexity: O(N).
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Comment
Article Tags: