题解 | #快速幂#

快速幂

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

import java.io.*;

/**
 * @BelongsProject: homework
 * @Author: Ling xi_Li
 * @CreateTime: 2023-11-09 17-41
 * @Description: TODO
 */

public class Main {
    public static void main(String[] args) throws IOException {
        //根据公式 (a1*a2)^b %p = ((a1%p)^b * (a2%p)^b) %p可以进行快速幂计算
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

        int n = Integer.parseInt(in.readLine());

        String[] lines = null;
        for (int i = 0; i < n; i++) {
            lines = in.readLine().split(" ");
            long a = Integer.parseInt(lines[0]);
            long b = Integer.parseInt(lines[1]);
            long p = Integer.parseInt(lines[2]);

            long res = 1;
		  //算法例子如:解pow(3, 10) = pow(9, 5) = res*pow(9, 4) = res*pow(81, 2) = res*pow(6561, 1)
		  // =res*a=res*6561
            while (b > 0) {
			  //指数为奇数时候,结果去乘以落单的a,指数-1为偶数
                if (b % 2 == 1) {
                    res *= a;
                    res %= p;
                    b--;
                }
			  //指数为偶数的时候,指数/2,底数平方
                b /= 2;
                a *=  a;
                a %= p;

            }
            out.write(res + "\n");
        }
        in.close();
        out.close();
    }
}

全部评论

相关推荐

28小凳也想实习:项目不用一个业务一个轮子吗,刷牛客好多人说要一业务一轮子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务