LeetCode 372 Super Pow
2016-07-11 10:13
435 查看
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:
思路
由于直接ab%1337会溢出,b本身也会溢出,它是一个超大数,所以ab%1337我们变换成
(a%1337)*(a%1337) %1337*(a%1337)%1337……这样处理。具体看代码吧。一目了然。
算法需要利用的恒等式 (a*b)%c
= (a%c)*(b%c)%c,证明如下:
代码实现如下:
参考:discuss
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
思路
由于直接ab%1337会溢出,b本身也会溢出,它是一个超大数,所以ab%1337我们变换成
(a%1337)*(a%1337) %1337*(a%1337)%1337……这样处理。具体看代码吧。一目了然。
算法需要利用的恒等式 (a*b)%c
= (a%c)*(b%c)%c,证明如下:
设a/c=m,则mc+a%c =a;设b/c=n,则nc+b%c =b;于是 (a*b)%c = { (mc+a%c)*(nc+b%c ) }%c = {mcnc+(nc)*(a%c)+(mc)*(b%c)+(a%c)*(b%c)} % c (其中 mcnc+(nc)*(a%c)+(mc)*(b%c)可以整除c) = (a%c)*(b%c)%c
代码实现如下:
public int superPow(int a, int[] b) { int res = 1; for (int i = 0; i < b.length; i++) { res = pow(res, 10) * pow(a, b[i]) % 1337; } return res; } public int pow(int a, int b) { if (b == 0) return 1; if (b == 1) return a % 1337; return pow(a % 1337, b / 2) * pow(a % 1337, b - b / 2) % 1337; }
参考:discuss
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解