The Wayback Machine - https://web.archive.org/web/20240627104137/https://www.geeksforgeeks.org/find-last-digit-of-ab-for-large-numbers/
Open In App

Find Last Digit of a^b for Large Numbers

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.org
Algorithm :
 

  1. Since number are very large we store them as a string.
  2. Take last digit in base a.
  3. 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.

Below is the implementation of above algorithm. 
 

C++




// C++ code to find last digit of a^b
#include <bits/stdc++.h>
using namespace std;
 
// Function to find b % a
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 < strlen(b); i++)
        mod = (mod * 10 + b[i] - '0') % a;
 
    return mod; // return modulo
}
 
// function to find last digit of a^b
int 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 case
int main()
{
    char a[] = "117", b[] = "3";
    cout << LastDigit(a, b);
    return 0;
}


Java




// Java code to find last digit of a^b
import 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




def last_digit(a, b):
    a = int(a)
    b = int(b)
     
    # if a and b both are 0
    if a == 0 and b == 0:
        return 1
       
    # if exponent is 0
    if b == 0:
        return 1
       
    # if base is 0
    if a == 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 b % 4 == 0:
        res = 4
    else:
        res = b % 4
         
    # Find last digit in 'a' and compute its exponent
    num = pow(a, res)
     
    # Return last digit of num
    return num % 10
 
a = "117"
b = "3"
print(last_digit(a,b))
 
# This code is contributed by Naimish14.


C#




// 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
// php code to find last digit of a^b
 
// Function to find b % a
function 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^b
function 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.
?>


Javascript




<script>
 
// Javascript code to find last digit of a^b
 
// Function to find b % a
function 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^b
function 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 case
let a = "117";
let b = "3";
document.write(LastDigit(a, b));
 
// This code is contributed by _saurabh_jaiswal
 
</script>


Output : 

3

This article is reviewed by team geeksforgeeks. 

 



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
Last digit of Product of two Large or Small numbers (a * b)
Given two large or small numbers, the task is to find the last digit of the product of these two numbers.Examples: Input: a = 1234567891233789, b = 567891233156156 Output: 4 Input: a = 123, b = 456 Output: 8 Approach: In general, the last digit of multiplication of 2 numbers a and b is the last digit of the product of the LSB of these two numbers.
3 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
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 N-digit numbers having digit XOR as single digit
Given an integer N, the task is to find the total count of N-Digit numbers such that the Bitwise XOR of the digits of the numbers is a single digit. Examples: Input: N = 1Output: 9Explanation: 1, 2, 3, 4, 5, 6, 7, 8, 9 are the numbers. Input: N = 2Output: 66Explanation: There are 66 such 2-digit numbers whose Xor of digits is a single digit number.
14 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
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
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
Print all 3 digit repeating numbers in a very large number
Given a very large number, print all the 3 digit repeating numbers with their frequency. If a 3 digit number appears more than once, print the number and its frequency. Example: Input: 123412345123456 Output: 123 - 3 times 234 - 3 times 345 - 2 times Input: 43243243 Output: 432 - 2 times 324 - 2 times 243 - 2 times Approach: Since the number is ver
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg