![]() |
VOOZH | about |
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.
Table of Content
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.
1 3 3
The idea of this approach is to use Matrix Exponentiation to efficiently compute the Nth Fibonacci number and then extract its 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.
1 3 3
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:
Consider n = 67, since 67 % 60 = 7 and the 7th Fibonacci number is 13, its last digit is 3.
1 3 3