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
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
這道題題讓我們求一個數的很大的次方對1337取余的值,開始一直在想這個1337有什么玄機,為啥突然給這么一個數,感覺很突兀,后來想來想去也沒想出來為啥,估計就是怕結果太大無法表示,隨便找個數取余吧。那么這道題和之前那道Pow(x, n)的解法很類似,我們都得對半縮小,不同的是后面都要加上對1337取余。由於給定的指數b是一個一維數組的表示方法,我們要是折半縮小處理起來肯定十分不方便,所以我們采用按位來處理,比如223 = (22)10 * 23, 所以我們可以從b的最高位開始,算出個結果存入res,然后到下一位是,res的十次方再乘以a的該位次方再對1337取余,參見代碼如下:
class Solution { public: int superPow(int a, vector<int>& b) { long long res = 1; for (int i = 0; i < b.size(); ++i) { res = pow(res, 10) * pow(a, b[i]) % 1337; } return res; } int pow(int x, int n) { if (n == 0) return 1; if (n == 1) return x % 1337; return pow(x % 1337, n / 2) * pow(x % 1337, n - n / 2) % 1337; } };
類似題目:
參考資料:
https://discuss.leetcode.com/topic/50430/c-ac-recursive-solution