【模板】快速幂

codevs 3500快速幂入门 有误,详解在 右上题解上。被坑了好久。

非递归版

qer的while

#include <iostream>
#include <queue>
using namespace std;
typedef long long LL;

LL a, b, k;

LL ksm(LL a, LL b, LL k)
{
    LL ans = 1;
    while(b)
    {
        if(b&1)
            ans = ((ans%k)*(a%k))%k;
        b >>= 1;
        a = ((a%k)*(a%k))%k;
    }
    return ans%k;
}

int main()
{
    cin >> a >> b >> k;
    cout << ksm(a,b,k) << endl;
    return 0;
}

qer的for(我一直在用的)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;
typedef long long LL;

LL ksm(LL a, LL p, LL k)
{
    LL ans = 1;
    for(; p; p >>= 1, a = ((a%k)*(a%k))%k)
        if(p&1)
            ans = ((ans%k)*(a%k))%k;
    return ans%k;
}

int main()
{
    LL a, b, c;
    cin >> a >> b >> c;
    printf("%lld^%lld mod %lld=%lld\n",a, b, c, ksm(a,b,c));
    return 0;
}


递归版

大神lcy的递归

//lcy 
LL ksm(int n, int m)
{
    if(m == 0) return 1; 
    if(m == 1) return n;
    if(n == 0) return 0;
    if(n == 1) return 1;
    LL ans = ksm(n, m >> 1);
    if(m % 2) return ans * ans * n;
    else return ans * ans;
}

大神DQS的递归

//dqs
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

int mod;

int ksm(int a,int b)
{
/*  int ans = 1;
    while(b)
    {
        if(b & 1) ans = ((ans % mod) * (a % mod)) % mod;
        a = ((a % mod) * (a % mod)) % mod;
        b >>= 1;
    }
    return ans;*/
    if(b == 0) return 1;
    if(b == 1) return a % mod;
    if(b % 2 == 1)
    {
        int tmp = ksm(a,b/2);
        return (((tmp % mod) * (tmp % mod)) % mod * (a % mod)) % mod;
    }
    else
    {
        int tmp = ksm(a,b/2);
        return ((tmp % mod) * (tmp % mod)) % mod;
    }
}

int main()
{
    int a,b;
    scanf("%d%d%d",&a,&b,&mod);
    printf("%d^%d mod %d=%d",a,b,mod,ksm(a,b));
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值