[算法]数学公式/快速幂

数学公式/快速幂

题目描述

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

思路解析
  1. 求余数可以用公式 (A*B)%C = (A%C * B%C)%C
  2. 求幂可以用快速幂
  3. 在快速幂的过程中求余数,可以很好的减少计算量,并防止溢出
快速幂的两种实现方式

实际上就是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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值