int s=1; while (b){ if (b&1) s=(longlong)s*a%p; a=(longlong)a*a%p; b>>=1; } cout<<s;
代码 py :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
print("Tell me a and b, I will output the last four numbers of a^b!\n") print("I can tell you the answer in O(log b) time!\n") a = int(input("a = ?\n")) # 输入 b = int(input("b = ?\n")) aa = a # 赋值,便于输出时使用 bb = b p = 10000# p是模数 s = 1# s是当前答案 # 接下来的注释假设循环了q次 while b > 0: if b % 2 == 1: # 如果b的二进制表示下最后一位是1,也就是我们需要计算a^(2^q) s = s * a % p # 那就将答案乘上a(现在的a已经是a^(2^q)了) a = a * a % p # a是不断平方的,循环q次,a就是原先的a^(2^q) b = b//2# b将二进制表示下最后一位删去 print("The last four numbers of ",aa,"^",bb," is ",s%p) # 输出