I am writing a function that is supposed to do powers, but only display the last n digits specified. It is working great… mostly. For some reason when I specify how many of the last digits I want, it works fine all the way up to and including the number 12. Any digit amount above 12 seems to give me a very strange number. I know I must be missing something obvious, but I really don’t see it.
Here is the code:
function power(base, exponent, digits) {
total = base;
for(i = 1; i < exponent; i++) {
total = total * base;
if(total.toString().length > digits) {
total = total.toString().substr(total.toString().length - digits, digits);
}
}
return total;
}
So, for some examples (displaying 12 digits and lower works fine):
If I do power(999, 999, 1) I end up with => 9
If I do power(999, 999, 5) I end up with => 98999
If I do power(999, 999, 12) I end up with => 000499998999
Here is where it starts messing up:
If I do power(999, 999, 13) I end up with => 5710054009000
If I do power(999, 999, 14) I end up with => ‘79077027006000’
At first I thought I was hitting some kind of integer limit and scientific notation was screwing things up, but I don’t think that is the case, because it should work up to 20 digits.
I suspect it is something wrong with the way I am reducing the string in the if statement. But I am not sure why it wouldn’t mess up for calculations below 13 digits.
Thanks!
You need a function to compute b^e (mod m). A good algorithm is known as square and multiply:
Then to make your computation, say PowerMod(999, 999, 10^14); you should get 17000499998999.