两个高效幂运算对比

#include <iostream>
#include
"MyTimer.h"

using namespace std;
int pow(int n,int k){
if(k==0) return 1;
if(k==1) return n;
if(k&1) return pow(n*n,k/2)*n;
return pow(n*n,k/2);
}

int power (int n, int k){//经实测,比pow快
int ret = n , a = ret;
--k;
while (k){
if (k & 1) ret = ret * a;
a
= a * a;
k
>>=1;
}
return ret;
}

int main() {
int n,k;
MyTimer mt;
while (cin>>n>>k){
mt.Start();
cout
<<pow(n,k);
mt.Stop();
cout
<<" "<<mt.costTime<<" us "<<endl;
mt.Reset();
mt.Start();
cout
<<power(n,k);
mt.Stop();
cout
<<" "<<mt.costTime<<" us "<<endl;
}
return 0;
}

posted @ 2011-04-20 22:43  wwwwwwwww11we  阅读(241)  评论(0编辑  收藏  举报