您的位置:首页 > 其它

Fast Power

2016-08-18 04:57 302 查看
Calculate the an % b where a, b and n are all 32bit integers.

Analyse: divide and conquer. Be aware of overflow.

Runtime: 12ms

class Solution {
public:
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
int fastPower(int a, int b, int n) {
// write your code here
if (!a || b == 1 || n < 0) return 0;
if (!n && b != 1) return 1;
if (n == 1) return a % b;

long temp1 = fastPower(a, b, n / 2);
long temp = temp1 * temp1 % b;
if (n % 2) temp *= a % b;
return (int)(temp % b);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: