#include <iostream>
#include <time.h>
using namespace std;
//普通求幂:求后三位的方法“模的乘法运算”
int normalPower(long long base,long long power)
{
long long result=1;
int i;
for(i=1;i<=power;i++)
{
result=result*base;
result=result%1000;
}
return result%1000;
}
//基础版快速幂
int quickPower1(long long base,long long power)
{
long long result=1;
while(power)
{
if(power%2==0)
{
power=power/2;
base=base*base%1000;
}
else
{
power=power-1;
result=result*base%1000;
power=power/2;
base=base*base%1000;
}
}
return result;
}
//改良版快速幂
int quickPower2(long long base,long long power)
{
long long result=1;
while(power)
{
if(power%2==1)
{
result=result*base%1000;
}
power/=2;
base=base*base%1000;
}
return result;
}
//究极版快速幂
int quickPower3(long long base,long long power)
{
long long result=1;
while(power)
{
if(power&1)
{
result=result*base%1000;
}
power>>=1;
base=base*base%1000;
}
return result;
}
int main()
{
long long base,power;
clock_t start,finish;
while(true)
{
//测试基础版快速幂
cin>>base>>power;
if(base==0&&power==0)
break;
start=clock();
cout<<quickPower1(base,power)<<endl;
finish=clock();
cout<<double(finish-start)/CLOCKS_PER_SEC<<endl;
//改良版快速幂
cin>>base>>power;
if(base==0&&power==0)
break;
start=clock();
cout<<quickPower2(base,power)<<endl;
finish=clock();
cout<<double(finish-start)/CLOCKS_PER_SEC<<endl;
//究极版快速幂:可是实测究极版竟然更慢诶,为什么
cin>>base>>power;
if(base==0&&power==0)
break;
start=clock();
cout<<quickPower3(base,power)<<endl;
finish=clock();
cout<<double(finish-start)/CLOCKS_PER_SEC<<endl;
//测试普通求幂
cin>>base>>power;
if(base==0&&power==0)
break;
start=clock();
cout<<normalPower(base,power)<<endl;
finish=clock();
cout<<double(finish-start)/CLOCKS_PER_SEC<<endl;
}
}
转载:超详细的快速幂