The Wayback Machine - https://web.archive.org/web/20240627104138/https://www.geeksforgeeks.org/program-find-last-digit-nth-fibonnaci-number/
Open In App

Program to find last digit of n’th Fibonacci Number

Last Updated : 09 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number ‘n’, write a function that prints the last digit of n’th (‘n’ can also be a large number) Fibonacci number. 
Examples : 
 

Input : n = 0
Output : 0

Input: n = 2
Output : 1

Input : n = 7
Output : 3

 

Recommended Practice

Method 1 : (Naive Method) 
Simple approach is to calculate the n’th Fibonacci number and printing the last digit. 
 

C++




// C++ Program to find last digit
// of nth Fibonacci number
#include <bits/stdc++.h>
using namespace std;
 
typedef long long int ll;
 
void multiply(ll F[2][2], ll M[2][2]);
void power(ll F[2][2], ll n);
 
// Function that returns
// nth Fibonacci number
ll fib(int n)
{
    ll F[2][2] = {{1, 1}, {1, 0}};
    if (n == 0)
        return 0;
    power(F, n - 1);
    return F[0][0];
}
 
// Utility method to find
// n'th power of F[][]
void power(ll F[2][2], ll n)
{
    // Base cases
    if (n == 0 || n == 1)
        return;
 
    ll M[2][2] = {{1, 1}, {1, 0}};
 
    power(F, n / 2);
    multiply(F, F);
 
    if (n % 2 != 0)
        multiply(F, M);
}
 
// Utility function to multiply two
// matrices and store result in first.
void multiply(ll F[2][2], ll M[2][2])
{
    ll x = F[0][0] * M[0][0] +
           F[0][1] * M[1][0];
    ll y = F[0][0] * M[0][1] +
           F[0][1] * M[1][1];
    ll z = F[1][0] * M[0][0] +
           F[1][1] * M[1][0];
    ll 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] = w;
}
 
// Returns last digit of
// n'th Fibonacci Number
int findLastDigit(int n)
{
return fib(n) % 10;
}
 
// Driver code
int main()
{
    ll n = 1;
    cout << findLastDigit(n) << endl;
    n = 61;
    cout << findLastDigit(n) << endl;
    n = 7;
    cout << findLastDigit(n) << endl;
    n = 67;
    cout << findLastDigit(n) << endl;
    return 0;
}


Java




// Java program to find last digit
// of nth Fibonacci number
class GFG
{
    // Function that returns
    // nth Fibonacci number
    static long fib(long n)
    {
        long F[][] = new long[][] {{1, 1}, {1, 0}};
        if (n == 0)
            return 0;
        power(F, n - 1);
 
        return F[0][0];
    }
 
    // Utility function to multiply two
    // matrices and store result in first.
    static void multiply(long F[][], long M[][])
    {
        long x = F[0][0] * M[0][0] +
                 F[0][1] * M[1][0];
        long y = F[0][0] * M[0][1] +
                 F[0][1] * M[1][1];
        long z = F[1][0] * M[0][0] +
                 F[1][1] * M[1][0];
        long 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] = w;
    }
 
    // Optimized version of power() in method 4
    static void power(long F[][], long n)
    {
        if( n == 0 || n == 1)
            return;
        long M[][] = new long[][] {{1, 1}, {1, 0}};
 
        power(F, n / 2);
        multiply(F, F);
 
        if (n % 2 != 0)
            multiply(F, M);
    }
 
    // Returns last digit of
    // n'th Fibonacci Number
    long findLastDigit(long n)
    {
        return (fib(n) % 10);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n;
        GFG ob = new GFG();
        n = 1;
        System.out.println(ob.findLastDigit(n));
        n = 61;
        System.out.println(ob.findLastDigit(n));
        n = 7;
        System.out.println(ob.findLastDigit(n));
        n = 67;
        System.out.println(ob.findLastDigit(n));
    }
}


Python3




# Python3 program to find last digit of
# nth Fibonacci number
 
# Function that returns nth Fibonacci number
def fib(n):
 
    F = [[1, 1], [1, 0]];
    if (n == 0):
        return 0;
    power(F, n - 1);
 
    return F[0][0];
 
# Utility function to multiply two
# matrices and store result in first.
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] = w;
 
# Optimized version of power() in
# method 4
def power(F, n):
 
    if( n == 0 or n == 1):
        return;
    M = [[1, 1], [1, 0]];
 
    power(F, int(n / 2));
    multiply(F, F);
 
    if (n % 2 != 0):
        multiply(F, M);
 
# Returns last digit of
# n'th Fibonacci Number
def findLastDigit(n):
 
    return (fib(n) % 10);
 
# Driver code
n = 1;
print(findLastDigit(n));
n = 61;
print(findLastDigit(n));
n = 7;
print(findLastDigit(n));
n = 67;
print(findLastDigit(n));
 
# This code is contributed
# by chandan_jnu


C#




// C# program to find last digit
// of nth Fibonacci number
using System;
 
class GFG
{
     
    // function that returns
    // nth Fibonacci number
    static long fib(long n)
    {
        long [,]F = new long[,] {{1, 1}, {1, 0}};
         
        if (n == 0)
            return 0;
             
        power(F, n - 1);
 
        return F[0, 0];
    }
 
    // Utility function to multiply two
    // matrices and store result in first.
    static void multiply(long [,]F, long [,]M)
    {
        long x = F[0, 0] * M[0, 0] +
                 F[0, 1] * M[1, 0];
        long y = F[0, 0] * M[0, 1] +
                 F[0, 1] * M[1, 1];
        long z = F[1, 0] * M[0, 0] +
                 F[1, 1] * M[1, 0];
        long 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] = w;
    }
 
    // Optimized version of power() in method 4
    static void power(long [,]F, long n)
    {
        if( n == 0 || n == 1)
            return;
        long [,]M = new long[,] {{1, 1}, {1, 0}};
 
        power(F, n / 2);
        multiply(F, F);
 
        if (n % 2 != 0)
            multiply(F, M);
    }
 
    // Returns last digit of
    // n'th Fibonacci Number
    static long findLastDigit(long n)
    {
        return (fib(n) % 10);
    }
 
    // Driver code
    public static void Main()
    {
        int n;
        n = 1;
        Console.WriteLine(findLastDigit(n));
        n = 61;
        Console.WriteLine(findLastDigit(n));
        n = 7;
        Console.WriteLine(findLastDigit(n));
        n = 67;
        Console.WriteLine(findLastDigit(n));
    }
}
 
// This code is contributed by Sam007.


PHP




<?php
// PHP program to find last digit of nth
// Fibonacci number
 
// Function that returns nth Fibonacci number
function fib($n)
{
    $F = array(array(1, 1),
               array(1, 0));
    if ($n == 0)
        return 0;
    power($F, $n - 1);
 
    return $F[0][0];
}
 
// Utility function to multiply two
// matrices and store result in first.
function 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] = $w;
}
 
// Optimized version of power() in method 4
function power(&$F, $n)
{
    if( $n == 0 || $n == 1)
        return;
    $M = array(array(1, 1), array(1, 0));
 
    power($F, (int)($n / 2));
    multiply($F, $F);
 
    if ($n % 2 != 0)
        multiply($F, $M);
}
 
// Returns last digit of
// n'th Fibonacci Number
function findLastDigit($n)
{
    return (fib($n) % 10);
}
 
// Driver code
$n = 1;
echo findLastDigit($n) . "\n";
$n = 61;
echo findLastDigit($n) . "\n";
$n = 7;
echo findLastDigit($n) . "\n";
$n = 67;
echo findLastDigit($n) . "\n";
 
// This code is contributed
// by Akanksha Rai


Javascript




<script>   
    // Javascript program to find last digit of nth Fibonacci number
     
    // Function that returns
    // nth Fibonacci number
    function fib(n)
    {
        let F = [[1, 1], [1, 0]];
        if (n == 0)
            return 0;
        power(F, n - 1);
  
        return F[0][0];
    }
  
    // Utility function to multiply two
    // matrices and store result in first.
    function multiply(F, M)
    {
        let x = F[0][0] * M[0][0] +
                 F[0][1] * M[1][0];
        let y = F[0][0] * M[0][1] +
                 F[0][1] * M[1][1];
        let z = F[1][0] * M[0][0] +
                 F[1][1] * M[1][0];
        let 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] = w;
    }
  
    // Optimized version of power() in method 4
    function power(F, n)
    {
        if( n == 0 || n == 1)
            return;
        let M = [[1, 1], [1, 0]];
  
        power(F, parseInt(n / 2, 10));
        multiply(F, F);
  
        if (n % 2 != 0)
            multiply(F, M);
    }
  
    // Returns last digit of
    // n'th Fibonacci Number
    function findLastDigit(n)
    {
        return (fib(n) % 10);
    }
     
    let n;
    n = 1;
    document.write(findLastDigit(n) + "</br>");
    n = 61;
    document.write(findLastDigit(n) + "</br>");
    n = 7;
    document.write(findLastDigit(n) + "</br>");
    n = 67;
    document.write(findLastDigit(n));
 
</script>


Output: 
 

1
1
3
3

Complexity: O(Log n).
Limitation of this implementation: 
Fibonacci numbers grow exponentially fast. For example, the 200’th Fibonacci number equals 280571172992510140037611932413038677189525. And F(1000) does not fit into the standard C++ int type. 
To overcome this difficulty, instead of calculating n’th Fibonacci number, there is a direct algorithm to just calculate its last digit (that is, F(n) mod 10).
Method 2 : (Direct Method) 
Look at the final digit in each Fibonacci number – the units digit:
 

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...

Is there a pattern in the final digits?
 

0, 1, 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0, 7, ...

Yes! 
It takes a while before it is noticeable. In fact, the series is just 60 numbers long and then it repeats the same sequence again and again all the way through the Fibonacci series – for ever. The series of final digits repeats with a cycle length of 60 (Refer this for explanations of this result).
So, instead of calculating the Fibonacci number again and again, pre-compute the units digit of first 60 Fibonacci number and store it in an array and use that array values for further calculations. 
 

C++




// Optimized Program to find last
// digit of nth Fibonacci number
#include<bits/stdc++.h>
using namespace std;
 
typedef long long int ll;
 
// Finds nth fibonacci number
ll fib(ll f[], ll n)
{
    // 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 <= n; i++)
        f[i] = (f[i - 1] + f[i - 2]) % 10;
 
    return f[n];
}
 
// Returns last digit of n'th Fibonacci Number
int findLastDigit(int n)
{
    ll f[60] = {0};
 
    // Precomputing units digit of 
    // first 60 Fibonacci numbers
    fib(f, 60);
 
    return f[n % 60];
}
 
// Driver code
int main ()
{
    ll n = 1;
    cout << findLastDigit(n) << endl;
    n = 61;
    cout << findLastDigit(n) << endl;
    n = 7;
    cout << findLastDigit(n) << endl;
    n = 67;
    cout << findLastDigit(n) << endl;
    return 0;
}


Java




// Optimized Java program to find last
// digit of n'th Fibonacci number
class GFG
{
    // Filongs f[] with first
    // 60 Fibonacci numbers
    void fib(int f[])
    {
        // 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 (int i = 2; i <= 59; i++)
            f[i] = (f[i - 1] + f[i - 2]) % 10;
    }
 
    // Returns last digit of n'th Fibonacci Number
    int findLastDigit(long n)
    {
        // In Java, values are 0 by default
        int f[] = new int[60];
 
        // Precomputing units digit of
        // first 60 Fibonacci numbers
        fib(f);
     
        int index = (int)(n % 60L);
 
        return f[index];
    }
 
    // Driver code
    public static void main(String[] args)
    {
        long n;
        GFG ob = new GFG();
        n = 1;
        System.out.println(ob.findLastDigit(n));
        n = 61;
        System.out.println(ob.findLastDigit(n));
        n = 7;
        System.out.println(ob.findLastDigit(n));
        n = 67;
        System.out.println(ob.findLastDigit(n));
    }
}


Python3




# Optimized Python3 Program to find last
# digit of nth Fibonacci number
 
# Finds nth fibonacci number
def fib(f, n):
 
    # 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, n + 1):
        f[i] = (f[i - 1] + f[i - 2]) % 10;
 
    return f;
 
# Returns last digit of n'th
# Fibonacci Number
def findLastDigit(n):
    f = [0] * 61;
 
    # Precomputing units digit of
    # first 60 Fibonacci numbers
    f = fib(f, 60);
 
    return f[n % 60];
 
# Driver code
n = 1;
print(findLastDigit(n));
n = 61;
print(findLastDigit(n));
n = 7;
print(findLastDigit(n));
n = 67;
print(findLastDigit(n));
 
# This code is contributed
# by chandan_jnu


C#




// Optimized C# program to find last
// digit of n'th Fibonacci number
using System;
 
class GFG {
 
    // Filongs f[] with first
    // 60 Fibonacci numbers
    static void fib(int []f)
    {
         
        // 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 (int i = 2; i <= 59; i++)
            f[i] = (f[i - 1] + f[i - 2]) % 10;
    }
 
    // Returns last digit of n'th
    // Fibonacci Number
    static int findLastDigit(long n)
    {
        int []f = new int[60];
 
        // Precomputing units digit of
        // first 60 Fibonacci numbers
        fib(f);
     
        int index = (int)(n % 60L);
 
        return f[index];
    }
 
    // Driver Code
    public static void Main()
    {
        long n;
        n = 1;
        Console.WriteLine(findLastDigit(n));
        n = 61;
        Console.WriteLine(findLastDigit(n));
        n = 7;
        Console.WriteLine(findLastDigit(n));
        n = 67;
        Console.WriteLine(findLastDigit(n));
    }
}
 
// This code is contributed by Sam007


PHP




<?php
// Optimized PHP Program to find last
// digit of nth Fibonacci number
 
// Finds nth fibonacci number
function fib(&$f, $n)
{
    // 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 = 2; $i <= $n; $i++)
        $f[$i] = ($f[$i - 1] +
                  $f[$i - 2]) % 10;
 
    return $f[$n];
}
 
// Returns last digit of n'th
// Fibonacci Number
function findLastDigit($n)
{
    $f = array_fill(0, 60, 0);
 
    // Precomputing units digit of
    // first 60 Fibonacci numbers
    fib($f, 60);
 
    return $f[$n % 60];
}
 
// Driver code
$n = 1;
print(findLastDigit($n) . "\n");
$n = 61;
print(findLastDigit($n) . "\n");
$n = 7;
print(findLastDigit($n) . "\n");
$n = 67;
print(findLastDigit($n) . "\n");
 
// This code is contributed
// by chandan_jnu
?>


Javascript




<script>
    // Optimized Javascript program to find last
    // digit of n'th Fibonacci number
     
    // Filongs f[] with first
    // 60 Fibonacci numbers
    function fib(f)
    {
           
        // 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 <= 59; i++)
            f[i] = (f[i - 1] + f[i - 2]) % 10;
    }
   
    // Returns last digit of n'th
    // Fibonacci Number
    function findLastDigit(n)
    {
        let f = new Array(60);
        f.fill(0);
   
        // Precomputing units digit of
        // first 60 Fibonacci numbers
        fib(f);
       
        let index = (n % 60);
   
        return f[index];
    }
     
    let n;
    n = 1;
    document.write(findLastDigit(n) + "</br>");
    n = 61;
    document.write(findLastDigit(n) + "</br>");
    n = 7;
    document.write(findLastDigit(n) + "</br>");
    n = 67;
    document.write(findLastDigit(n) + "</br>");
     
    // This code is contributed by divyesh072019
</script>


Output: 
 

1
1
3
3

Complexity: O(1).

 



Previous Article
Next Article

Similar Reads

Last digit of a number raised to last digit of N factorial
Given two number X and N, the task is to find the last digit of X raised to last digit of N factorial, i.e. [Tex]X^{\left ( N! \right )mod 10} [/Tex].Examples: Input: X = 5, N = 2 Output: 5 Explanation: Since, 2! mod 10 = 2 therefore 52 = 25 and the last digit of 25 is 5.Input: X = 10, N = 4 Output: 0 Explanation: Since, 4! mod 10 = 24 mod 10 = 4 t
15 min read
Find the remainder when First digit of a number is divided by its Last digit
Given a number N, find the remainder when the first digit of N is divided by its last digit.Examples: Input: N = 1234 Output: 1 First digit = 1 Last digit = 4 Remainder = 1 % 4 = 1 Input: N = 5223 Output: 2 First digit = 5 Last digit = 3 Remainder = 5 % 3 = 2 Approach: Find the first digit and the last digit of the number. Find then the remainder w
5 min read
Last digit of sum of numbers in the given range in the Fibonacci series
Given two non-negative integers M, N which signifies the range [M, N] where M ? N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Examples: Input: M = 3, N = 9 Output: 6 Explanation: We need to find F3 + F4 + F5 + F6 +
5 min read
Count of Numbers in Range where first digit is equal to last digit of the number
Given a range represented by two positive integers L and R. Find the count of numbers in the range where the first digit is equal to the last digit of the number. Examples: Input : L = 2, R = 60 Output : 13 Explanation : Required numbers are 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44 and 55 Input : L = 1, R = 1000 Output : 108 Prerequisites: Digit DPTh
15+ min read
Program to find last two digits of Nth Fibonacci number
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 “PRACTICE” first, before moving on to the solution. A simple solution is to find n-th Fibonacci number and print its last two
9 min read
Count ways to generate N digit number such that its every digit divisible by previous digit
Given a number N, the task is to count the number of ways to create an N digit number from digits 1 to 9 such that every digit is divisible by its previous digit that is if the number is represented by an array of digits A then A[i + 1] % A[i] == 0. print the answer modulo 109 + 7. Examples: Input: N = 2Output: 23Explanation: For N = 2 possible ans
15+ min read
Check if a M-th fibonacci number divides N-th fibonacci number
Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n
8 min read
Count numbers in a range with digit sum divisible by K having first and last digit different
Given a range in the form of L and R, and a value K, the task is to count the numbers between the range L to R such that the sum of the digit is divisible by K, and the first digit is not equal to the last digit of the number. Examples: Input: L = 1, R = 10, K = 2 Output: 0 Explanation: The input numbers whose sum of the digits are divisible by 2 (
15 min read
Count of pairs (A, B) in range 1 to N such that last digit of A is equal to the first digit of B
Given a number N, the task is to find the number of pairs (A, B) in the range [1, N] such that the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.Examples: Input: N = 25 Output: 17 Explanation: The pairs are: (1, 1), (1, 11), (2, 2), (2, 22), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8),
5 min read
Arrange array elements such that last digit of an element is equal to first digit of the next element
Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element. Examples: Input: arr[] = {123, 321} Output: 123 321 Input: arr[] = {451, 378, 123, 1254} Output: 1254 451 123 378 Recommended: Please try your approach on {IDE} first, before moving on to th
15+ min read
three90RightbarBannerImg