[LintCode] Fast Power
生活随笔
收集整理的這篇文章主要介紹了
[LintCode] Fast Power
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Problem
Calculate the a^n % b where a, b and n are all 32bit integers.
Example
For 2^31 % 3 = 2
For 100^1000 % 1000 = 0
Challenge
O(logN)
Note
應用求余公式: (a * b) % p = (a % p * b % p) % p
使用分治法,不斷分解a^n為a^(n/2),最終的子問題就是求解a^1或者a^0的余數。
唯一要注意的就是,若n為奇數,要將余數和a再代入求余公式,運算一次。
Solution
class Solution {public int fastPower(int a, int b, int n) {if (n == 0) return 1 % b;if (n == 1) return a % b;long product = fastPower(a, b, n/2);product = product * product % b;if (n % 2 == 1) product = product * a % b;return (int) product;} }總結
以上是生活随笔為你收集整理的[LintCode] Fast Power的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nginx的负载均衡 - 保持会话 (i
- 下一篇: Quartz教程二:API,Job和Tr