[LeetCode]372. Super Pow

本文介绍了一种高效计算 a^b mod 1337 的算法,其中 a 是正整数,b 是一个非常大的正整数数组。通过递归分解幂次,利用模运算的性质来降低计算复杂度。

https://leetcode.com/problems/super-pow/#/description

Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.





a ^ 123456 % 1337 = (a ^ 123450 % 1337) * (a ^ 6 % 1337) % 1337 = ((a ^ 12345) ^ 10 % 1337) * (a ^ 6 % 1337) % 1337

mod(a, b, k) = (a ^ b) % k

public class Solution {
    public int superPow(int a, int[] b) {
        return superPow(a, b, b.length, 1337);
    }
    private int superPow(int a, int[] b, int n, int k) {
        if (n == 1) {
            return mod(a, b[0], k);
        }
        return mod(superPow(a, b, n - 1, k), 10, k) * mod(a, b[n - 1], k) % k;
    }
    private int mod(int a, int b, int k) {
        a %= k;
        int res = 1;
        for (int i = 0; i < b; i++) {
            res = res * a % k;
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值