VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-find-last-digit-nth-fibonnaci-number/

⇱ Program to find last digit of n'th Fibonacci Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find last digit of n'th Fibonacci Number

Last Updated : 8 May, 2026

Given a number n, find the last digit of the nth Fibonacci number. The Fibonacci sequence is a series in which each number is the sum of the previous two numbers, where F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n >= 2.

Examples:

Input: n = 7
Output: 3
Explanation: Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, ... The 7th Fibonacci number is 13. So, the last digit is 3.

Input: n = 61
Output: 1
Explanation: Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, ... The 61st Fibonacci number ends with 1. So, the last digit is 1.

[Naive Approach] Generate Complete Fibonacci Numbers - O(n) Time and O(1) Space

The idea of this approach is to generate Fibonacci numbers iteratively while storing only their last digits. Instead of storing the complete Fibonacci numbers, we keep only the last digit by taking modulo 10.

  • Initialize two variables a and b as 0 and 1.
  • a stores the previous Fibonacci number's last digit.
  • b stores the current Fibonacci number's last digit.
  • For every iteration:
  • Calculate the next Fibonacci number using (a + b) % 10.
  • Update a and b and Finally, return b.

Output
1
3
3

[Better Approach] Matrix Exponentiation - O(log n) Time and O(log n) Space

The idea of this approach is to use Matrix Exponentiation to efficiently compute the Nth Fibonacci number and then extract its last digit.

  • Fibonacci numbers follow a matrix pattern: {{1 1}, {1 0}}.
  • If we raise this matrix to the power (n - 1), we get: {{F(n) F(n-1)}, {F(n-1) F(n-2)}}.
  • So, the value at F[0][0] gives the Nth Fibonacci number. Finally, we return F[0][0] % 10 to get the last digit.

Consider n = 7, we compute F^(6) of matrix {{1, 1}, {1, 0}}, and after exponentiation we get {{13, 8}, {8, 5}}, so F[0][0] = 13 and the last digit is 13 % 10 = 3.


Output
1
3
3

[Expected Approach] Using Pisano Period - O(1) Time and O(1) Space

The idea of this approach is based on the fact that the last digits of Fibonacci numbers repeat in a fixed cycle. The last digits are: 0, 1, 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, ... This sequence repeats after every 60 numbers. This repeating cycle is called the Pisano Period for modulo 10.

So instead of generating Fibonacci numbers repeatedly:

  • Precompute the last digits of the first 60 Fibonacci numbers.
  • Store them in an array.
  • Find the required index using n % 60.
  • Return the value at that index.

Consider n = 67, since 67 % 60 = 7 and the 7th Fibonacci number is 13, its last digit is 3.


Output
1
3
3
Comment