[Leetcode] 372. Super Pow 解题报告
来源:互联网 发布:table用js做点击事件 编辑:程序博客网 时间:2024/06/06 00:31
题目:
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 = 2b = [3]Result: 8
Example2:
a = 2b = [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; }};
阅读全文
0 0
- [leetcode] 372. Super Pow 解题报告
- [Leetcode] 372. Super Pow 解题报告
- Leetcode 372. Super Pow 快速幂计算 解题报告
- leetcode.372. Super Pow
- LeetCode 372. Super Pow
- [LEETCODE] 372. super pow
- LeetCode--372. Super Pow
- leetcode 372. Super Pow
- Leetcode 372. Super Pow
- [leetcode] 372. Super Pow
- Leetcode: 372.Super Pow
- 372. Super Pow(LeetCode)
- LeetCode 372. Super Pow
- [LeetCode]372. Super Pow
- [leetcode]372. Super Pow
- leetcode 372. Super Pow
- LeetCode 372. Super Pow解题思路(超详细)
- LeetCode—372. Super Pow
- unity中的几个Update
- android代码管理工具 HG Mercurial commit之前没有pull,冲突解决
- android path 详解
- linux网络编程中INADDR_ANY的含义
- gulp使用
- [Leetcode] 372. Super Pow 解题报告
- nuget 导致 vs hang死
- 工作日记2017.08.21 Google Guava
- HttpClient
- leetcode 409. Longest Palindrome
- Android源码目录结构详解
- opengl对图像进行模糊处理
- ajaxfileupload文件上传插件,解决再次提交文件流置空的问题
- 常见状态码