Find Last Digit of a^b for Large Numbers

13 Apr, 2021
You are given two integer numbers, the base a (number of digits d, such that 1 <= d <= 1000) and the index b (0 <= b <= 922*10^15). You have to find the last digit of a^b.Examples:  
Input  : 3 10
Output : 9

Input  : 6 2
Output : 6

Input  : 150 53
Output : 0
 
After taking few examples, we can notice below pattern. 
Number  |  Last digits that repeat in cycle
  1     |     1
  2     |  4, 8, 6, 2
  3     |  9, 7, 1, 3
  4     |  6, 4
  5     |  5
  6     |  6
  7     |  9, 3, 1, 7
  8     |  4, 2, 6, 8
  9     |  1, 9
In the given table, we can see that maximum length for cycle repetition is 4. Example: 2*2 = 4*2 = 8*2 = 16*2 = 32 last digit in 32 is 2 that means after multiplying 4 times digit repeat itself. So the algorithm is very simple .Source : Brilliants.orgAlgorithm : 
Since number are very large we store them as a string.Take last digit in base a.Now calculate b%4. Here b is very large. If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram.If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram.Now calculate ldigit = pow( last_digit_in_base, exp ).Last digit of a^b will be ldigit%10.
Since number are very large we store them as a string.
Take last digit in base a.
Now calculate b%4. Here b is very large. If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram.If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram.Now calculate ldigit = pow( last_digit_in_base, exp ).Last digit of a^b will be ldigit%10.
If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram.
If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram.
Now calculate ldigit = pow( last_digit_in_base, exp ).
Last digit of a^b will be ldigit%10.
Below is the implementation of above algorithm.  
C++
Java
C#
PHP
Javascript
// C++ code to find last digit of a^b#include <bits/stdc++.h>using namespace std; // Function to find b % aint Modulo(int a, char b[]){    // Initialize result    int mod = 0;     // calculating mod of b with a to make    // b like 0 <= b < a    for (int i = 0; i < strlen(b); i++)        mod = (mod * 10 + b[i] - '0') % a;     return mod; // return modulo} // function to find last digit of a^bint LastDigit(char a[], char b[]){    int len_a = strlen(a), len_b = strlen(b);     // if a and b both are 0    if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0')        return 1;     // if exponent is 0    if (len_b == 1 && b[0] == '0')        return 1;     // if base is 0    if (len_a == 1 && a[0] == '0')        return 0;     // if exponent is divisible by 4 that means last    // digit will be pow(a, 4) % 10.    // if exponent is not divisible by 4 that means last    // digit will be pow(a, b%4) % 10    int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b);     // Find last digit in 'a' and compute its exponent    int res = pow(a[len_a - 1] - '0', exp);     // Return last digit of result    return res % 10;} // Driver program to run test caseint main(){    char a[] = "117", b[] = "3";    cout << LastDigit(a, b);    return 0;}
// Java code to find last digit of a^bimport java.io.*;import java.math.*; class GFG {     // Function to find b % a    static int Modulo(int a, char b[])    {        // Initialize result        int mod = 0;         // calculating mod of b with a to make        // b like 0 <= b < a        for (int i = 0; i < b.length; i++)            mod = (mod * 10 + b[i] - '0') % a;         return mod; // return modulo    }     // Function to find last digit of a^b    static int LastDigit(char a[], char b[])    {        int len_a = a.length, len_b = b.length;         // if a and b both are 0        if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0')            return 1;         // if exponent is 0        if (len_b == 1 && b[0] == '0')            return 1;         // if base is 0        if (len_a == 1 && a[0] == '0')            return 0;         // if exponent is divisible by 4 that means last        // digit will be pow(a, 4) % 10.        // if exponent is not divisible by 4 that means last        // digit will be pow(a, b%4) % 10        int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b);         // Find last digit in 'a' and compute its exponent        int res = (int)(Math.pow(a[len_a - 1] - '0', exp));         // Return last digit of result        return res % 10;    }     // Driver program to run test case    public static void main(String args[]) throws IOException    {        char a[] = "117".toCharArray(), b[] = { '3' };        System.out.println(LastDigit(a, b));    }} // This code is contributed by Nikita Tiwari.
Python3 

# Python 3 code to find last digit of a ^ b

import math

# Function to find b % a
def Modulo(a, b) :
    # Initialize result
    mod = 0

    # calculating mod of b with a to make
    # b like 0 <= b < a
    for i in range(0, len(b)) :
        mod = (mod * 10 + (int)(b[i])) % a

    return mod # return modulo


# function to find last digit of a ^ b
def LastDigit(a, b) :
    len_a = len(a)
    len_b = len(b)

    # if a and b both are 0
    if (len_a == 1 and len_b == 1 and b[0] == '0' and a[0] == '0') :
        return 1

    # if exponent is 0
    if (len_b == 1 and b[0]=='0') :
        return 1

    # if base is 0
    if (len_a == 1 and a[0] == '0') :
        return 0

    # if exponent is divisible by 4 that means last
    # digit will be pow(a, 4) % 10.
    # if exponent is not divisible by 4 that means last
    # digit will be pow(a, b % 4) % 10
    if((Modulo(4, b) == 0)) :
        exp = 4
    else : 
        exp = Modulo(4, b)

    # Find last digit in 'a' and compute its exponent
    res = math.pow((int)(a[len_a - 1]), exp)

    # Return last digit of result
    return res % 10
    

# Driver program to run test case
a = ['1', '1', '7']
b = ['3']
print(LastDigit(a, b))

# This code is contributed to Nikita Tiwari.

// C# code to find last digit of a^b.using System; class GFG {     // Function to find b % a    static int Modulo(int a, char[] b)    {                 // Initialize result        int mod = 0;         // calculating mod of b with a        // to make b like 0 <= b < a        for (int i = 0; i < b.Length; i++)            mod = (mod * 10 + b[i] - '0') % a;         // return modulo        return mod;    }     // Function to find last digit of a^b    static int LastDigit(char[] a, char[] b)    {        int len_a = a.Length, len_b = b.Length;         // if a and b both are 0        if (len_a == 1 && len_b == 1 &&                   b[0] == '0' && a[0] == '0')            return 1;         // if exponent is 0        if (len_b == 1 && b[0] == '0')            return 1;         // if base is 0        if (len_a == 1 && a[0] == '0')            return 0;         // if exponent is divisible by 4        // that means last digit will be        // pow(a, 4) % 10. if exponent is        //not divisible by 4 that means last        // digit will be pow(a, b%4) % 10        int exp = (Modulo(4, b) == 0) ? 4                            : Modulo(4, b);         // Find last digit in 'a' and        // compute its exponent        int res = (int)(Math.Pow(a[len_a - 1]                                - '0', exp));         // Return last digit of result        return res % 10;    }     // Driver program to run test case    public static void Main()    {                 char[] a = "117".ToCharArray(),        b = { '3' };                 Console.Write(LastDigit(a, b));    }} // This code is contributed by nitin mittal.
<?php// php code to find last digit of a^b // Function to find b % afunction Modulo($a, $b){         // Initialize result    $mod = 0;     // calculating mod of b with a to make    // b like 0 <= b < a    for ($i = 0; $i < strlen($b); $i++)        $mod = ($mod * 10 + $b[$i] - '0') % $a;     return $mod; // return modulo} // function to find last digit of a^bfunction LastDigit($a, $b){    $len_a = strlen($a); $len_b = strlen($b);     // if a and b both are 0    if ($len_a == 1 && $len_b == 1 &&                $b[0] == '0' && $a[0] == '0')        return 1;     // if exponent is 0    if ($len_b == 1 && $b[0] == '0')        return 1;     // if base is 0    if ($len_a == 1 && $a[0] == '0')        return 0;     // if exponent is divisible by 4 that    // means last digit will be pow(a, 4)    // % 10. if exponent is not divisible    // by 4 that means last digit will be    // pow(a, b%4) % 10    $exp = (Modulo(4, $b) == 0) ? 4 :                              Modulo(4, $b);     // Find last digit in 'a' and compute    // its exponent    $res = pow($a[$len_a - 1] - '0', $exp);     // Return last digit of result    return $res % 10;} // Driver program to run test case$a = "117";$b = "3";echo LastDigit($a, $b); // This code is contributed by nitin mittal.?>
<script> // Javascript code to find last digit of a^b // Function to find b % afunction Modulo(a, b){         // Initialize result    let mod = 0;     // calculating mod of b with a to make    // b like 0 <= b < a    for (let i = 0; i < b.length; i++)        mod = (mod * 10 + b[i] - '0') % a;     return mod; // return modulo} // function to find last digit of a^bfunction LastDigit(a, b){    let len_a = a.length;    let len_b = b.length;     // if a and b both are 0    if (len_a == 1 && len_b == 1 &&                b[0] == '0' && a[0] == '0')        return 1;     // if exponent is 0    if (len_b == 1 && b[0] == '0')        return 1;     // if base is 0    if (len_a == 1 && a[0] == '0')        return 0;     // if exponent is divisible by 4 that    // means last digit will be pow(a, 4)    // % 10. if exponent is not divisible    // by 4 that means last digit will be    // pow(a, b%4) % 10    exp = (Modulo(4, b) == 0) ? 4 :                            Modulo(4, b);     // Find last digit in 'a' and compute    // its exponent    res = Math.pow(a[len_a - 1] - '0', exp);     // Return last digit of result    return res % 10;} // Driver program to run test caselet a = "117";let b = "3";document.write(LastDigit(a, b)); // This code is contributed by _saurabh_jaiswal </script>
Output : 
3
This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team geeksforgeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
_saurabh_jaiswal
large-numbers
Modular Arithmetic
Samsung
Mathematical
Samsung
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)