def power(A,N,M):
ret=1
while(N):
if(N%2!=0):ret=(ret*A)%M
A=(A*A)%M
N=N//2
return ret
The built-in pow function does exactly this, if you give it three
arguments:
>>> pow(12345, 67891, 17)
10
>>> 12345 ** 67891 % 17
10L
(Though this won't work for negative N.)
Mark
It doesn't do 'exactly' that. M is the number of digits.
If you want 17 digits, the third number should 10**17.
Using 17 directly will give you a 2-digit answer as shown.
Try this instead:
>>> pow(12345,67891,10**17)
50553131103515625
How do you arrive at log N as the performance number?
DaveA
By the way, given that your M is fairly tiny compared with A and N, a
little bit of elementary number theory (e.g., Euler's theorem) could
save you a lot of time here. For example,
pow(a, n, 10**5)
is equivalent to
pow(a, 5 + (n - 5) % 40000, 10**5)
for any n >= 5. Not sure if this is the kind of thing you're looking
for.
--
Mark