您的位置:首页 > 其它

[Leetcode] 372. Super Pow 解题报告

2017-08-24 10:24 465 查看
题目

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

思路

不知道出题人为什么会想出来1337这么奇怪的数字?好像1337也不是素数。

这里需要用到两个关键的数学公式:

1) a^b % c = (a % c)^b % c;

2) ab % c = (a % c) * (b % c) % c。

其中1)可以让我们尽可能地缩减a的值,2)可以让我们递归地缩减b的值。当然为了防止溢出,我们需要自己实现一个计算(a^k % c)的函数。

代码

class Solution {
public:
    int superPow(int a, vector<int>& b) {
        if(b.empty()) {
            return 1;
        } 
        a = a % 1337;                                                       // a^b % c = (a % c)^b % c
        int last = b.back();  
        b.pop_back();  
        return (superPow(superPow(a, b), 10) * superPow(a, last)) % 1337;   // a^(10b + c) = a^(10b) * a^c = (a^b)^10 * a^c
    }
private:
    int superPow(int a, int k) {  
        if(k == 0) {
            return 1; 
        }
        int ans = 1;  
        for(int i = 1; i <= k; ++i) {                                       // ab % c = (a % c) * (b % c) % c
            ans = (ans * a) % 1337;
        }
        return ans;  
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: