寒假每日一题打卡day26—— AcWing 89. a^b

【题目描述】

在这里插入图片描述
AcWing 89. a^b

【思路】
快速幂求解。

import java.io.*;
public class Main{
    //0≤a,b≤109  1≤p≤109
    public static long quick_pow(long a, long b, long p){
        if( b == 1) return  a % p;
        if( b == 0) return 1 % p;
        long ans = 1;
        long t = a;
        while( b != 0){
            //奇数则乘以a
            if( (b & 1) == 1) ans = (ans * t) % p;
            t = (t * t) % p; //成乘方式扩大
            b = b >>1;
        }
        return ans % p;
    }
    public static void main(String args[]) throws Exception{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
        String s[] = bf.readLine().split(" ");
        long a = Integer.parseInt(s[0]), b = Integer.parseInt(s[1]),  p= Integer.parseInt(s[2]);
        long ans = quick_pow(a, b, p);
        log.write(ans+"\n");
        log.flush();
        log.close();
        bf.close();
    }
}
import java.util.Scanner;

public class Main {
    public static long quickPow(long a, int b, int c){
        long ans = 1;
        while(b > 0){
            // 如果b的二进制表示最低位为1则乘上当前的a
            if((b&1)==1){
                ans = ans * a % c;
            }
            // 更新a,a依次为 a^{2^0}, a^{2^1},  a^{2^2}, ……, a^{2^logb}
            a = a * a % c;
            b >>= 1;
        }
        return ans;
    }
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		int n = reader.nextInt();
		for(int i  = 0; i < n; i ++){
		    int a = reader.nextInt(), b = reader.nextInt(), c = reader.nextInt();
		    System.out.println(quickPow(a, b , c));
		    
		}
		

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值