最近在看密码学的时候看到了快速幂取模运算,在这里记录一下思路;
算例
算例还是用手写的了,方便一点;
代码
下面来模拟一下上面的计算:
- import fire
- import pdb
- import logging
- logging.basicConfig(level=logging.ERROR)
- def fast_mod(x, n, m):
- """
- x^n(mod m)
- """
- logging.info("To Calcuate %d^%d(mod %d)" % (x,n,m))
- logging.info("--- --- ---")
- a = 1
- b = x
- loop=1
- while True:
- temp = n
- logging.info("a=%d,b=%d,n=%d" % (a,b,n))
- if n % 2 == 1 :
- a_t = a
- a = a * b % m
- logging.info("Loop:%d, ans = %d * %d mod(%d) = %d" % (loop,a_t,b,m,a))
- else:
- logging.info("Loop:%d, Keep %d" % (loop,a))
- b_tmp = b
- b = b * b % m
- logging.info("b = %d * %d mod(%d) = %d" % (b_tmp,b_tmp,m,b))
- n = n//2
- loop=loop+1
- logging.info("--- --- ---")
- #pdb.set_trace()
- if temp < 1 :
- return a
- def main():
- fire.Fire(fast_mod)
- if __name__ == '__main__':
- main()
运行结果如下 :
验证一下计算结果是否正确:
- 微信公众号
- 关注微信公众号
- QQ群
- 我们的QQ群号
评论