今天開始整理一下做過的快速冪的問題
快速冪就是
第一題 Leetcode372
這道題有多種解法,可以看作快速冪,也可以不用快速冪解決。
解法1:
我嘗試使用c++來實現快速冪,不幸超時掛掉了。這裏轉別人一份java的代碼,同樣的原理,但是不太明白java爲什麼會過。
原文在此,這裏只是轉載這段代碼。
public class Solution {
/**
* 這道題是ACM裏面入門問題,powmod,詳細的算法可以參照這裏:http://blog.csdn.net/xuruoxin/article/details/8578992
* */
// 判斷是否大於0
public boolean morethanzero(int[] x){
for(int i=x.length-1;i>=0;i--){
if(x[i]>0) return true;
}
return false;
}
//高精度除法
public void div(int[] x,int y){
int tmp=0;
for(int i=0;i<x.length;i++){
x[i] += tmp*10;
tmp = x[i] % y;
x[i] = x[i] /y;
}
}
public int superPow(int a, int[] b) {
if (morethanzero(b) == false) return 1;
a=a%1337;
boolean isEven = false;
if(b[b.length-1] % 2 == 0) isEven = true;
div(b,2);
int result = superPow(a,b);
result = result % 1337;
result*=result;
result = result % 1337;
if(isEven==false){
result*=a;
result = result % 1337;
}
return result;
}
}
解法2:
快速冪超時了,結合這道題的特點,它使用數組存儲了很大的b,我就按位來求,
class Solution {
public:
static int powmod(int a, int b){
int ret=1;
for (int i=0; i<b; ++i) {
ret=(ret*a)%1337;
}
return ret;
}
int superPow(int a, vector<int>& b) {
if (b.empty()) {
return 1;
}
a=a%1337;
int last=b.back();
b.pop_back();
return (powmod(superPow(a, b),10)*powmod(a, last))%1337;
}
};