2021寒假每日一题《a^b》

a^b

题目来源:《算法竞赛进阶指南》
时间限制:\(1000ms\) 内存限制:\(32mb\)

题目描述

\(a\)\(b\) 次方对 \(p\) 取模的值。

输入格式

三个整数 \(a\) , \(b\) , \(p\) ,在同一行用空格隔开。

输出格式

输出一个整数,表示 a^b mod p 的值。

数据范围

\(0 ≤ a,b,p ≤ 10^9\) ,
数据保证 \(p≠0\)

样例输入

3 2 7

样例输出

2

解题思路

这是一个快速幂模板题,直接套模板就可以了。

快速幂模板(\(a^b\%p\)):

public static long quickPow(int a, int b, int mod) {
    long ans = 1, clothCover = a;
    while (b > 0) {
        if ((b & 1) == 1) {
            ans = ans * clothCover % mod;
        }
        clothCover = clothCover * clothCover % mod;
        b >>= 1;
    }
    return ans % mod;
}

解题代码-Java

import java.util.Scanner;

public class Main {
    public static long quickPow(int a, int b, int mod) {
        long ans = 1, clothCover = a;
        while (b > 0) {
            if ((b & 1) == 1) {
                ans = ans * clothCover % mod;
            }
            clothCover = clothCover * clothCover % mod;
            b >>= 1;
        }
        return ans % mod;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println(quickPow(input.nextInt(), input.nextInt(), input.nextInt()));
        input.close();
    }
}
posted @ 2021-02-04 02:14  胡人天  阅读(124)  评论(0编辑  收藏  举报