Find Last Digit of a^b for Large Numbers in C++


In this problem, we are given two numbers a and b. Our task is to find Last Digit of a^b for Large Numbers. 

Let’s take an example to understand the problem, 

Input: a = 4 b = 124

Output: 6

Explanation: 

The value of a^b is 4.523128486 * 1074

Solution Approach

The solution to the problem is based on the fact that all the exponents of a number will be repeated after 4 exponent values.

So, we will find the value of b%4. Also, for any base value, the last digit of its power is decided by the last digit of the base value.

So, the resultant value will be calculated as

Last value of a  ^ (b%4)

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int calcModulus(char b[], int a)
{
   int mod = 0;

   for (int i = 0; i < strlen(b); i++)
      mod = (mod * 10 + b[i] - '0') % a;

   return mod;
}

int calcLastDigitInExpo(char a[], char b[]) {

   int len_a = strlen(a), len_b = strlen(b);

   if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0')
      return 1;
   if (len_b == 1 && b[0] == '0')
      return 1;
   if (len_a == 1 && a[0] == '0')
      return 0;

   int exponent = (calcModulus(b, 4) == 0) ? 4 : calcModulus(b, 4);
   int base = a[len_a - 1] - '0';
   int result = pow(base, exponent);
   return result % 10;
}

int main()
{
   char a[] = "559", b[] = "4532";
   cout<<"The last digit in of the value is "<<calcLastDigitInExpo(a, b);
   return 0;
}

Output

The last digit in of the value is 1

Updated on: 25-Jan-2021

666 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements