Fast Power
2016-07-23 04:57
274 查看
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
分析:
利用公式:
(a * b) % p = (a % p * b % p) % p
a^n % b = (a^(n/2) * a^(n/2) * (a)) %b = ((a^(n/2) * a^(n/2))%b * (a)%b) %b = ((a^(n/2)%b * a^(n/2)%b)%b * (a)%b) %b
Example
For 2^31 % 3 = 2
For 100^1000 % 1000 = 0
分析:
利用公式:
(a * b) % p = (a % p * b % p) % p
a^n % b = (a^(n/2) * a^(n/2) * (a)) %b = ((a^(n/2) * a^(n/2))%b * (a)%b) %b = ((a^(n/2)%b * a^(n/2)%b)%b * (a)%b) %b
class Solution { /* * @param a, b, n: 32bit integers * @return: An integer */ public int fastPower(int a, int b, int n) { if (a == 0) return 0; if (n == 0) return 1 % b; if (n == 1 || a == 1) return a % b; long temp = fastPower(a, b, n / 2); temp = temp * temp; temp = temp % b; if (n % 2 == 1) { temp = temp * (a % b); return (int)(temp % b); } else { return (int)temp; } } };
相关文章推荐
- Generate Parentheses
- 关于在MySQL中实现upsert操作
- 利用无线网卡建立个人wifi hotspot
- codeforces 701C They Are Everywhere(尺取法)
- POJ1328-Radar Installation
- 【CSS】其他CSS属性和特性
- ST表与二分 (CodeForces 689D-Friends and Subsequences)
- jvm 配置,看看
- Reverse Words in a String II
- Git命令小总结
- Unity各个函数的执行顺序
- Intersection of Two Arrays
- Codeforces Round #364 (Div. 2) 题解
- 面试基础
- 利用jar命令打包和解压
- JavaScript创建对象
- 【C++11】C++11新增的便利算法[1] all_of、any_of 和 none_of
- 暴力枚举,dfs(连连看,HDU 4272)
- DroidPlugin源码分析服务与静态广播的处理
- 算法-巴什博奕