I have created a function to compute large modular exponents. I am aware that this function is built into the python language. My function is incorrect for numbers with larger than 17 digits, and I can't figure out why. Any help is greatly appreciated.
from random import randint
def modpow(x,n,m):
if n == 0:
return 1
elif n == 1:
return x
elif n%2 == 0:
return modpow(x*(x%m),n/2,m)%m
elif n%2 == 1:
return (x * modpow(x*(x%m),(n-1)/2,m)%m )%m
for i in range(5,32):
x = ''
n = ''
m = ''
for j in range(i):
x += str(randint(0,9))
n += str(randint(0,9))
m += str(randint(0,9))
x = int(x)
n = int(n)
m = int(m)
if pow(x,n,m) != modpow(x,n,m):
print(i,x,n,m)
Sample output:
17 38508450670424585 67111951647554134 59005802612594983
18 24027200512104766 205942669690724726 816654795945860553
...
I've run this several times and it always starts failing at i = 17, I'm not quite sure why.