[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:
Example2:
思路:
不知道出题人为什么会想出来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)的函数。
代码:
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; } };
相关文章推荐
- [leetcode] 372. Super Pow 解题报告
- LeetCode 372. Super Pow解题思路(超详细)
- LeetCode-Pow(x, n)-解题报告
- [LeetCode] Pow(x, n) 解题报告
- [LeetCode]pow(double x,int n)解题报告
- leetcode_372. Super Pow
- leetcode_372. Super Pow ? 待解决
- leetcode 313 Super ugly number 解题报告
- LeetCode: Pow(x, n) 解题报告
- [LeetCode] Pow(x, n) 解题报告
- LeetCode解题报告—— Group Anagrams & Pow(x, n) & Spiral Matrix
- LeetCode50 Pow(x, n) 解题报告
- [leetcode] 1. Two Sum 解题报告
- 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告
- [Leetcode] 138. Copy List with Random Pointer 解题报告
- [leetcode] 258. Add Digits 解题报告
- [leetcode] 243. Shortest Word Distance 解题报告
- LeetCode 423. Reconstruct Original Digits from English 解题报告
- [leetcode] 28. Implement strStr() 解题报告
- LeetCode 1. Two Sum 解题报告