快速幂算法

#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;
    }
}

转载:超详细的快速幂

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值