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