|
幂模算法
附件没法上传,就贴在这里了
#!/usr/bin/python
#a, b , c
# a^b mod c
import math
def m_mod(a,b,c) :
l_v = math.log(c, a)
if(l_v > b) :
#print "pow(%d, %d) < %d"%(a, b, c )
return pow(a,b)
i_l_v = int(l_v) + 1
count=b / i_l_v
mod_p = (pow(a,i_l_v) )% c
#print "pow(%d, %d) mod %d is %d" % (a, i_l_v, c, mod_p)
#print "Should pow %d times ."% (count)
t_mod1 = 1
_l_v = int (math.log(c, a)) +1
if(count > _l_v * 2):
t_mod1 = m_mod(mod_p, count, c)
else:
t_mod1 = pow(mod_p, count ) % c
r= b % i_l_v
t_mod2 = pow(a, (b % i_l_v))
res = (t_mod1 * t_mod2 )% c
#print "%d ^ %d mod %d = %d " %(a,b,c,res)
return res
a1=911
b1=45646487979878974564446465465464646461313415464647989789652379
c1=45646487979878974564446465465464646461313415464647989789652379
res1 = m_mod(a1, b1, c1)
a2=9
b2=29341213421321329341213421321329341213421321352525656547752525656547729341213421
c2=29341213421321329341213421321329341213421321352525656547752525656547729341213421
res2 = m_mod(a2, b2, c2)
c3=321315464567857987946584543541352132134165465458978979879879798797987987123546235413L
a3=113
b3=c3-1
res3 = m_mod(a3, b3, c3)
print "%d ^ %d mod %d = %d " %(a1,b1,c1,res1)
print "%d ^ %d mod %d = %d " %(a2,b2,c2,res2)
print "%d ^ %d mod %d = %d " %(a3,b3,c3,res3)
|
|