I'm looking for a way to square a number n
, x
times and get the answer in modulo m
(m is prime)?
For example, if n = 5, x = 3 and m = 7, it would be (((5^2)^2)^2) % 7 = 390625 % 7 = 4
I tried exponentiation by squaring (I have a function called modularPow
that accepts base
, power
, mod
), and in this case it would simply be modularPow(5, 2^3, 7)
, which produces the correct answer. But the problem is, that x can be very big, even 10^12, so I would have to do modularPow(5, 2^(10^12), 7)
, which won't work. Is there any better way to do it? Preferably in Javascript, but Python would also work for me