Program to find last digit of n'th Fibonacci Number (original) (raw)
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
- [Naive Approach] Generate Complete Fibonacci Numbers - O(n) Time and O(1) Space
- [Better Approach] Matrix Exponentiation - O(log n) Time and O(log n) Space
- [Expected Approach] Using Pisano Period - O(1) Time and O(1) Space
[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. C++ `
#include <bits/stdc++.h> using namespace std;
// Function to find last digit // of Nth Fibonacci number int fib(int n) {
// Base cases
if (n == 0)
return 0;
if (n == 1)
return 1;
int a = 0;
int b = 1;
// Calculate last digit of Fibonacci number
for (int i = 2; i <= n; i++) {
// Store previous value of b
int c = b;
// Store only last digit
b = (a + b) % 10;
// Update a
a = c;
}
// Return last digit
return b;}
int main() {
cout << fib(61) << endl;
cout << fib(7) << endl;
cout << fib(67) << endl;
return 0;}
Java
public class GFG {
// Function to find last digit
// of Nth Fibonacci number
static int fib(int n) {
// Base cases
if (n == 0)
return 0;
if (n == 1)
return 1;
int a = 0;
int b = 1;
// Calculate last digit of Fibonacci number
for (int i = 2; i <= n; i++) {
// Store previous value of b
int c = b;
// Store only last digit
b = (a + b) % 10;
// Update a
a = c;
}
// Return last digit
return b;
}
public static void main(String[] args) {
System.out.println(fib(61));
System.out.println(fib(7));
System.out.println(fib(67));
}}
Python
Function to find last digit
of Nth Fibonacci number
def fib(n):
# Base cases
if n == 0:
return 0
if n == 1:
return 1
a = 0
b = 1
# Calculate last digit of Fibonacci number
for i in range(2, n + 1):
# Store previous value of b
c = b
# Store only last digit
b = (a + b) % 10
# Update a
a = c
# Return last digit
return bif name == "main":
print(fib(61))
print(fib(7))
print(fib(67))C#
using System;
class GFG {
// Function to find last digit
// of Nth Fibonacci number
static int fib(int n) {
// Base cases
if (n == 0)
return 0;
if (n == 1)
return 1;
int a = 0;
int b = 1;
// Calculate last digit of Fibonacci number
for (int i = 2; i <= n; i++) {
// Store previous value of b
int c = b;
// Store only last digit
b = (a + b) % 10;
// Update a
a = c;
}
// Return last digit
return b;
}
static void Main() {
Console.WriteLine(fib(61));
Console.WriteLine(fib(7));
Console.WriteLine(fib(67));
}}
JavaScript
// Function to find last digit // of Nth Fibonacci number function fib(n) {
// Base cases
if (n === 0)
return 0;
if (n === 1)
return 1;
let a = 0;
let b = 1;
// Calculate last digit of Fibonacci number
for (let i = 2; i <= n; i++) {
// Store previous value of b
let c = b;
// Store only last digit
b = (a + b) % 10;
// Update a
a = c;
}
// Return last digit
return b;}
// Drive code console.log(fib(61)); console.log(fib(7)); console.log(fib(67));
`
[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.
C++ `
#include <bits/stdc++.h> using namespace std;
typedef long long int ll;
// Matrix multiplication void multiply(ll F[2][2], ll M[2][2]) { ll x = (F[0][0] * M[0][0] + F[0][1] * M[1][0]) % 10;
ll y = (F[0][0] * M[0][1] +
F[0][1] * M[1][1]) % 10;
ll z = (F[1][0] * M[0][0] +
F[1][1] * M[1][0]) % 10;
ll w = (F[1][0] * M[0][1] +
F[1][1] * M[1][1]) % 10;
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;}
// Utility function to compute power of matrix void power(ll F[2][2], ll n) { // Base cases if (n == 0 || n == 1) return;
ll M[2][2] = {{1, 1}, {1, 0}};
// Recursive call
power(F, n / 2);
// Multiply matrix with itself
multiply(F, F);
// If n is odd, multiply one more time
if (n % 2 != 0)
multiply(F, M);}
// Returns last digit of nth Fibonacci number int fib(int n) { ll F[2][2] = {{1, 1}, {1, 0}};
// Base case
if (n == 0)
return 0;
// Find (n-1)th power of matrix
power(F, n - 1);
// Return last digit
return F[0][0] % 10;}
int main() { cout << fib(61) << endl; cout << fib(7) << endl; cout << fib(67) << endl; return 0; }
Java
class Main {
// Matrix multiplication
static void multiply(long F[][], long M[][])
{
long x = (F[0][0] * M[0][0] +
F[0][1] * M[1][0]) % 10;
long y = (F[0][0] * M[0][1] +
F[0][1] * M[1][1]) % 10;
long z = (F[1][0] * M[0][0] +
F[1][1] * M[1][0]) % 10;
long w = (F[1][0] * M[0][1] +
F[1][1] * M[1][1]) % 10;
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
// Utility function to compute power of matrix
static void power(long F[][], long n)
{
// Base cases
if (n == 0 || n == 1)
return;
long M[][] = {{1, 1}, {1, 0}};
// Recursive call
power(F, n / 2);
// Multiply matrix with itself
multiply(F, F);
// If n is odd, multiply one more time
if (n % 2 != 0)
multiply(F, M);
}
// Returns last digit of nth Fibonacci number
static int fib(int n)
{
long F[][] = {{1, 1}, {1, 0}};
// Base case
if (n == 0)
return 0;
// Find (n-1)th power of matrix
power(F, n - 1);
// Return last digit
return (int)(F[0][0] % 10);
}
// Driver code
public static void main(String[] args)
{
int n = 61;
System.out.println(fib(n));
n = 7;
System.out.println(fib(n));
n = 67;
System.out.println(fib(n));
}}
Python
def multiply(F, M):
x = F[0][0] * M[0][0] + \
F[0][1] * M[1][0]
y = F[0][0] * M[0][1] + \
F[0][1] * M[1][1]
z = F[1][0] * M[0][0] + \
F[1][1] * M[1][0]
w = F[1][0] * M[0][1] + \
F[1][1] * M[1][1]
F[0][0] = x
F[0][1] = y
F[1][0] = z
F[1][1] = wdef power(F, n):
# Base cases
if n == 0 or n == 1:
return
M = [[1, 1],
[1, 0]]
# Recursive call
power(F, n // 2)
# Multiply matrix with itself
multiply(F, F)
# If n is odd, multiply one more time
if n % 2 != 0:
multiply(F, M)Returns last digit of nth Fibonacci number
def fib(n):
F = [[1, 1],
[1, 0]]
# Base case
if n == 0:
return 0
# Find (n-1)th power of matrix
power(F, n - 1)
# Return last digit
return F[0][0] % 10if name == "main":
n = 61
print(fib(n))
n = 7
print(fib(n))
n = 67
print(fib(n))C#
using System;
class GFG {
// Matrix multiplication
static void multiply(long[,] F, long[,] M)
{
long x = (F[0, 0] * M[0, 0] +
F[0, 1] * M[1, 0]) % 10;
long y = (F[0, 0] * M[0, 1] +
F[0, 1] * M[1, 1]) % 10;
long z = (F[1, 0] * M[0, 0] +
F[1, 1] * M[1, 0]) % 10;
long w = (F[1, 0] * M[0, 1] +
F[1, 1] * M[1, 1]) % 10;
F[0, 0] = x;
F[0, 1] = y;
F[1, 0] = z;
F[1, 1] = w;
}
// Utility function to compute power of matrix
static void power(long[,] F, long n)
{
// Base cases
if (n == 0 || n == 1)
return;
long[,] M = {{1, 1}, {1, 0}};
// Recursive call
power(F, n / 2);
// Multiply matrix with itself
multiply(F, F);
// If n is odd, multiply one more time
if (n % 2 != 0)
multiply(F, M);
}
// Returns last digit of nth Fibonacci number
static int fib(int n)
{
long[,] F = {{1, 1}, {1, 0}};
// Base case
if (n == 0)
return 0;
// Find (n-1)th power of matrix
power(F, n - 1);
// Return last digit
return (int)(F[0, 0] % 10);
}
static void Main()
{
int n = 61;
Console.WriteLine(fib(n));
n = 7;
Console.WriteLine(fib(n));
n = 67;
Console.WriteLine(fib(n));
}}
JavaScript
// Matrix multiplication function multiply(F, M) { let x = (F[0][0] * M[0][0] + F[0][1] * M[1][0]) % 10;
let y = (F[0][0] * M[0][1] +
F[0][1] * M[1][1]) % 10;
let z = (F[1][0] * M[0][0] +
F[1][1] * M[1][0]) % 10;
let w = (F[1][0] * M[0][1] +
F[1][1] * M[1][1]) % 10;
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;}
// Utility function to compute power of matrix function power(F, n) { // Base cases if (n === 0 || n === 1) return;
let M = [[1, 1], [1, 0]];
// Recursive call
power(F, Math.floor(n / 2));
// Multiply matrix with itself
multiply(F, F);
// If n is odd, multiply one more time
if (n % 2 !== 0)
multiply(F, M);}
// Returns last digit of nth Fibonacci number function fib(n) { let F = [[1, 1], [1, 0]];
// Base case
if (n === 0)
return 0;
// Find (n-1)th power of matrix
power(F, n - 1);
// Return last digit
return F[0][0] % 10;}
// Driver code let n = 61; console.log(fib(n));
n = 7; console.log(fib(n));
n = 67; console.log(fib(n));
`
[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.
C++ `
#include<bits/stdc++.h> using namespace std;
typedef long long int ll;
// Returns last digit of nth Fibonacci Number int fib(int n) { ll f[60] = {0};
// 0th and 1st number of
// the series are 0 and 1
f[0] = 0;
f[1] = 1;
// Add the previous 2 numbers
// in the series and store
// last digit of result
for (ll i = 2; i < 60; i++)
f[i] = (f[i - 1] + f[i - 2]) % 10;
return f[n % 60];}
int main () { ll n = 61; cout << fib(n) << endl;
n = 7;
cout << fib(n) << endl;
n = 67;
cout << fib(n) << endl;
return 0;}
Java
public class GFG {
// Returns last digit of nth Fibonacci Number
static int fib(int n)
{
long f[] = new long[60];
// 0th and 1st number of
// the series are 0 and 1
f[0] = 0;
f[1] = 1;
// Add the previous 2 numbers
// in the series and store
// last digit of result
for (long i = 2; i < 60; i++)
f[(int)i] = (f[(int)i - 1] + f[(int)i - 2]) % 10;
return (int)f[n % 60];
}
public static void main(String[] args)
{
long n = 61;
System.out.println(fib((int)n));
n = 7;
System.out.println(fib((int)n));
n = 67;
System.out.println(fib((int)n));
}}
Python
Returns last digit of nth Fibonacci Number
def fib(n):
f = [0] * 60
# 0th and 1st number of
# the series are 0 and 1
f[0] = 0
f[1] = 1
# Add the previous 2 numbers
# in the series and store
# last digit of result
for i in range(2, 60):
f[i] = (f[i - 1] + f[i - 2]) % 10
return f[n % 60]if name == "main":
n = 61
print(fib(n))
n = 7
print(fib(n))
n = 67
print(fib(n))C#
using System;
class GFG {
// Returns last digit of nth Fibonacci Number
static int fib(int n)
{
long[] f = new long[60];
// 0th and 1st number of
// the series are 0 and 1
f[0] = 0;
f[1] = 1;
// Add the previous 2 numbers
// in the series and store
// last digit of result
for (long i = 2; i < 60; i++)
f[i] = (f[i - 1] + f[i - 2]) % 10;
return (int)f[n % 60];
}
static void Main()
{
long n = 61;
Console.WriteLine(fib((int)n));
n = 7;
Console.WriteLine(fib((int)n));
n = 67;
Console.WriteLine(fib((int)n));
}}
JavaScript
// Returns last digit of nth Fibonacci Number function fib(n) { let f = new Array(60).fill(0);
// 0th and 1st number of
// the series are 0 and 1
f[0] = 0;
f[1] = 1;
// Add the previous 2 numbers
// in the series and store
// last digit of result
for (let i = 2; i < 60; i++)
f[i] = (f[i - 1] + f[i - 2]) % 10;
return f[n % 60];}
// Drive code let n = 61; console.log(fib(n));
n = 7; console.log(fib(n));
n = 67; console.log(fib(n));
`