-2

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.

1 Answers1

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