JAVA 蓝桥杯 算法提高 快速幂
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
给定A, B, P,求(A^B) mod P。
输入格式
输入共一行。
第一行有三个数,N, M, P。
输出格式
输出共一行,表示所求。
样例输入
2 5 3
样例输出
2
数据规模和约定
共10组数据
对100%的数据,A, B为long long范围内的非负整数,P为int内的非负整数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
long c = sc.nextLong();
long pre=1;
a%=c;
while(b>0) {
if((b&1)==1) {
pre=(pre*a)%c;
}
a=(a*a)%c;
b>>=1;
}
System.out.println(pre);
}
}