标签:
计算
直接求超时
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {
// write your code here
if(n==0){
return 1%b;
}
int result = 1;
for(int i=1;i<=n;i++){
result = result * a%b;
}
return result;
}
};
仿照求幂的方法
result要定义为Long,否则异常使结果错误
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {
// write your code here
if(n==0)
return 1%b;
if(n==1){
return a%b;
}
long result = fastPower(a,b,n/2);
result = (result * result)%b;
if(n%2==1){
result = result * a%b;
}
result = result%b;
return (int)result;
}
};
网上看到下面的快幂算法不知道为什么出错
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {
// write your code here
if(n==0)
return 1%b;
if(n==1){
return a%b;
}
long res = 1;
while(n> 0){
if((n&1)==1)
res = (res*a)%b;
n = n>>1;
a = (a * a)%b;
}
return (int)res;
}
};
标签:
原文地址:http://blog.csdn.net/qunxingvip/article/details/51778672