Question
Find the last k digits of the number nn. It is guaranteed that the length of number nn is not less than k.
Example
For n = 5, k = 3, the result should be "125"
5^5 = 3125, last 3 digits is "125"
Input / Output
[input] integer n
1 ≤ N ≤ 10^9
[input] integer k
1 ≤ k ≤ 9
[output] a string
string of length k ---> last k digits of n^n
My Code
function n2n(n, k) {
let a = Math.pow(n, n);
let b = Array.from(a.toString()).map(Number);
return b.slice((b.length-k),).join('');
}
console.log(n2n(5, 25));
console.log(n2n(5, 3));
console.log(n2n(1, 1));
console.log(n2n(5,4));
console.log(n2n(43, 7));
console.log(n2n(999, 9));
This code seems to work for the smaller numbers, but then fails with big numbers.
My theory is that it is because when the number gets really big it is no longer a typical number but becomes 5345354+e9325 or something like that.
Do you agree that my code works? Is there a way to prevent certain numbers bing processes as NaN.
The console logs in my code provides:
3125
125
1
3125
268NaNNaN70
NaN