The function returns the last digit of the number, but if the number is too large then infinity, how to handle the number so that infinity does not return?

var lastDigit = function(str1, str2){ var result = Math.pow(+str1,+str2).toString().split(''); var elem = +result[result.length - 1]; console.log(elem); }; 
 lastDigit("4", "1"); // 4 => 4 lastDigit("4", "2"); // 16 => 6 lastDigit("9", "7"); // 4782969 => 9 lastDigit("10","10000000000"); //=> 0 
  • one
    And then what should return? Use long arithmetic to find very large numbers. - user207618
  • I still need to process the number and get the last digit, but I can’t get it as result = infinity / - lesha310392
  • in the sense of long arithmetic? - lesha310392
  • This is just the remainder of dividing the last digit of str1 into 10 squares (probably it wasn’t multiplied by a long time?) - avp
  • @avp, this is for what occasion? for example, for 2 to the power of 7, the last digit would be 8 (128). According to your algorithm: 2 * 2% 10 = 4. Or did I misunderstand something? - Grundy

1 answer 1

You raise the first argument to the power expressed by the second argument and find the lowest decimal place of the result. To put it mathematically: x y (mod 10)

This is a classical problem of number theory, which has wide application and ready-made solutions that do not require x ^ y to be calculated separately.

The simplest algorithm is based on the fact that (a * b) (mod m) == (a * (b (mod m))) (mod m)

 function lastDigit(base, exponent) { var c = 1; for (i = 1; i <= exponent; i++) c = (c * base) % 10; return c; } 

There are other more efficient algorithms: Algorithms for rapid exponentiation modulo