@jtahstu
2017-06-08T20:25:50.000000Z
字数 640
阅读 2719
算法
求a的b次方对c取余的值
由公式:a^p mod m = (a mod m)^p mod m
典型的就是南阳OJ102题,次方求模
# author: jtusta# contact: root@jtahstu.com# site: http://www.jtahstu.com# software: RubyMine# time: 2017/6/9 03:54class PowMod# 循环写法def powMod(a,p,m)res = 1while p>0if p%2==1res = (res*a)%menda = (a*a)%mp >>= 1endresend# 递归写法def powMod_2(a,p,m)res = 1if p==0return 1%mendif p==1return a%mendres = self.powMod_2(a,p/2,m)res = res*res%mif p%2==1res = res*a%mendresendendtest = PowMod.newp test.powMod(11,12345,12345)p test.powMod_2(11,12345,12345)
运行结果
/usr/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/jtusta/Documents/Code/Ruby/algorithm/pow_mod.rb1048110481Process finished with exit code 0