LeetCode372.SuperPow

372. Super Pow(超级次方)

题目描述:

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.

Example1:
a = 2
b = [3]
Result: 8
Example2:
a = 2
b = [1,0]
Result: 1024

说明:理解题意,即计算 (a^b)%1377 的值(其中,a 是一个整数,b 是一个由数组表示的非常大的正整数)

要求:输入正整数 a,数组 b
返回 (a^b)%1337 的值

题解:

快速幂取模的变形,分析 f = (x^y)%k
对于 y = [t1,t2,t3,t4]
则 f = (x^(t1*1000+t2*100+t3*10+t4))
例如 y = [2,3,4,5] 则 f = (x^2345)%1337
即 f = ((x^1000)^2*(x^300)*(x^40)*(x^5))%k
 = ((x^1000)^2*(x^100)^3*(x^10)^4*(x^1)^5)%k

利用数学模运算基本公式 :·(a*b)%p = (a%p*b%p)%p· 
则,实现如下

Code:

package codimgTest1;

public class Mian {

    public static void main(String[] args){
        int[]y = new int[]{1,0};
        System.out.print( superPow(2,y));
    }

    public static int superPow(int x,int[] y){
         long ans = 1;
         long a = x;

        for(int i=y.length-1;i>=0;i--){
             ans = ans*newPow(a,y[i]%1377);
             a = newPow(a,10);

        }

         return (int)ans;

    }

    private static int newPow(long x, int y) {
        long ans = 1;
        long a = x;
        while (y > 0) {
            if ((y & 1) > 0) {
                ans = ans * a % 1377;
            }

            y >>= 1;
            a = a * a % 1377;
        }
        return (int) ans;

    }   

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值