I would like to know how to find the units digit of a number raised to another number without calculating the result of the operation, i.e 5**7 = 78125, so I want to write a function that returns 5 as the last digit of the operation.
Asked
Active
Viewed 86 times
-2
-
1https://brilliant.org/wiki/finding-the-last-digit-of-a-power/ – Ayush Gupta Oct 24 '19 at 12:50
-
More curious about why than how. – plalx Oct 24 '19 at 12:52
-
It's used when dealing with large numbers ! – hamza mohamed seifeddine Oct 24 '19 at 12:57
1 Answers
1
This link offer a simple algorithm that explains how to deal with such problem.
Identify the units digit in the base ‘x’ and call it say ‘l’. {For example, If x = 24, then the units digit in 24 is 4. Hence l = 4.} Divide the exponent ‘y’ by 4. If the exponent y is exactly divisible by 4. i.e, y leaves a remainder 0 when divided by 4. Then, the units digit of pow(x,y) is 6, if l = 2,4,6,8. the units digit of pow(x,y) is 1, if l =3,7,9. If y leaves a non-zero remainder r, when divided by 4 (i.e y = 4k + r). Then, the units digit of pow(x,y) = pow(I,r) .
A basic implementation of this algorithm :
function getLastDigit(x, y) {
const I = x % 10;
const r = y % 4;
if (r === 0) {
if (I === 2 || I === 4 || I === 6 || I === 8) {
return 6 % 10;
}
if (I === 3 || I === 7 || I === 9) {
return 1 % 10;
}
}
return I ** r % 10;
}
console.log(getLastDigit(2019, 2020));

Karim Chaari
- 340
- 1
- 8