- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Articles
- Find the last digit when factorial of A divides factorial of B in C++
- Find the sum of first and last digit for a number using C language
- Print all 3 digit repeating numbers in a very large number in C++
- Count of Numbers in Range where first digit is equal to last digit of the number in C++
- Program to find last digit of n’th Fibonnaci Number in C++
- C++ Program to Find Factorial of Large Numbers
- Divisible by 37 for large numbers in C++ Program
- Program to find last digit of the given sequence for given n in Python
- Sum of two large numbers in C++
- Find last five digits of a given five digit number raised to power five in C++
- Handling large numbers in C++?
- Large Fibonacci Numbers in C#
- Find (a^b)%m where ‘a’ is very large in C++
- Count n digit numbers not having a particular digit in C++
- Find records with a specific last digit in column with MySQL

Advertisements