题解 | 快速幂

快速幂

https://www.nowcoder.com/practice/defdedf4fe984c6c91eefa6b00d5f4f0

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();        
        while(T-- > 0){
            long a = in.nextLong(), b = in.nextLong(), p = in.nextLong();
            System.out.println(binpow(a,b,p));
        }
    }
    // 取模的运算不会干涉乘法运算,因此我们只需要在计算的过程中取模即可。
    static long binpow(long a, long b, long p){
        a %= p;
        long res = 1;
        while(b>0){
            if((b&1) == 1)
                res = res*a%p;
            a = a*a%p;
            b >>= 1;
        }
        return res;
    }
}

参考:https://oi-wiki.org/math/binary-exponentiation/#%E6%A8%A1%E6%84%8F%E4%B9%89%E4%B8%8B%E5%8F%96%E5%B9%82

快速幂模版啊。

全部评论

相关推荐

一天代码十万三:这都不能算简历吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务