数学公式/快速幂
题目描述
Description
Implement pow(A, B) % C.In other words, given A, B and C, find (A^B)%C
Input
The first line of input consists number of the test cases. The following T lines consist of 3 numbers each separated by a space and in the following order:A B C’A’ being the base number, ‘B’ the exponent (power to the base number) and ‘C’ the modular.Constraints:1 ≤ T ≤ 70,1 ≤ A ≤ 10^5,1 ≤ B ≤ 10^5,1 ≤ C ≤ 10^5
Output
In each separate line print the modular exponent of the given numbers in the test case.
Sample Input 1
3
3 2 4
10 9 6
450 768 517
Sample Output 1
1
4
34
题目解析
给定A B C,求(AB)%C
思路解析
- 求余数可以用公式 (A*B)%C = (A%C * B%C)%C
- 求幂可以用快速幂
- 在快速幂的过程中求余数,可以很好的减少计算量,并防止溢出
快速幂的两种实现方式
实际上就是3的6次方 =9的三次方 = … 而不是使用3 * 3 * 3…
前者复杂度是O(logN),后者是O(N)
递归
def fast(a, b):
if b == 0:
return 1
if b & 1 == 1: # 奇数
return a * fast(a, b - 1)
else: # 偶数
x = fast(a, b // 2)
return x * x
循环
def fast2(a, b):
ans = 1
while b > 0:
if b & 1 == 1:
ans *= a
a = a * a # a * a
b = b >> 1 # b/2
return ans
代码实现(python)
if __name__ == '__main__':
for _ in range(int(input())):
a, b, c = list(map(int, input().strip().split(" ")))
ans = 1
while b > 0:
if b & 1 == 1:
ans *= a
a = ((a % c) * (a % c)) % c
b = b >> 1
print(ans % c)