LeetCode——372. Super Pow

题目链接: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.

Example1:

a = 2
b = [3]

Result: 8

Example2:

a = 2
b = [1,0]

Result: 1024

计算一个a的b次幂,然后对1337取模。

刚开始没注意取模直接看Example就写了程序:

static int superPow(int a, int[] b) {
    int sub = 1,mod = 0,ex = 1;
    for(int i = b.length - 1; i >= 0; i--){
        mod += (b[i] * ex);
        ex *= 10;
    }
    System.out.println(mod);
    for(;mod > 0; mod--){
        sub = sub * a;
    }
    return sub;
}

本来以为直接对结果取模就行,但其实是会出现很大的问题的,因为题目说了这个a将是一个很大的数字,假如a的b次幂大于int的范围就会出错,所以不能在最后的结果取模。

用到的数学公式:a ^ b % p = ((a % p)^b) % p 

所以第二次修改就是:

static int superPow(int a, int[] b) {
    int sub = 1,mod = 0,ex = 1;
    for(int i = b.length - 1; i >= 0; i--){
        mod += (b[i] * ex);
        ex *= 10;
    }
    a = a%1337;
    System.out.println(mod);
    for(;mod > 0; mod--){
        sub = sub * a;
    }
    return sub%1337;
}

这里一开始就对a进行了取模运算,然后在求幂,最后再进行一次取模运算,得到结果。

然后还有问题,就是在求幂的时候也会超出范围。所以在求幂的时候也要注意不要超出范围。

这次用到的公式就是:(a * b) % p = (a % p * b % p) % p 

所以第三次修改就是:

static int superPow(int a, int[] b) {
    int sub = 1,mod = 0,ex = 1;
    for(int i = b.length - 1; i >= 0; i--){
        mod += (b[i] * ex);
        ex *= 10;
    }
    a = a%1337;
    System.out.println(mod);
    for(;mod > 0; mod--){
        sub = sub%1337 * a;
    }
    return sub%1337;
}

到目前为止幂的运算一直都没问题,一直忽略了b数组的读取,万一b数组代表的数是大于int的范围也同样会出错。

这里使用的公式大体就是:

a^123 = (a^3)^1*(a^2)^10*(a^1)^100;

class Solution {
    public int superPow(int a, int[] b) {
           int sub = 1, j = 1;
    for(int i = b.length - 1; i >= 0; i--) { 
        sub *=(Pow(Pow(a, b[i]), j))%1337;
        j *= 10;
    }
    return sub%1337;
    }
    int Pow(int a, int k) {
        int sub = 1;
        if(k == 0) return 1;
        a = a%1337;
        for(;k > 0; k--){
            sub = (sub %1337) * a;
        }
        return sub%1337;
    }
}

 

posted @ 2017-11-06 14:19  xxbbtt  阅读(304)  评论(0编辑  收藏  举报