快速幂
无函数快速幂
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
long long b, p, k;
scanf("%lld%lld%lld", &b, &p, &k);
long long s, a;
s = b%k;
a = 1;
for(int i=1; i<=p; i++)
{
s = s*b%k;
if(s==b%k) break;
a++;
}
printf("%lld^%lld mod %lld=", b, p, k);
p = p%a;
s = 1;
if(p==0) p=a;
for(int i=1; i<=p; i++) s=s*b%k;
printf("%lld", s);
return 0;
}
递归
#include<cstdio>
using namespace std;
int f(int x, int n, int m)
{
if(n == 0) return 1%m;
if(n == 1) return x%m;
long long y = f(x, n/2, m);
y = (y%m)*(y%m)%m;
if(n%2==1) y = (y%m)*(x%m)%m;
return y;
}
int main()
{
int x, n, m;
long long z;
scanf("%d %d %d", &x, &n, &m);
z = f(x, n, m);
printf("%d^%d mod %d=%lld", x, n, m, z);
return 0;
}
递推
#include<cstdio>
#define ll long long
using namespace std;
ll pow(ll a, ll b, ll n)
{
ll ans=1;
while(b)
{
if(b%2 == 1) ans*=a;
a = (a*a)%n;
b=b/2;
}
return ans;
}
ll a, b, n;
int main()
{
scanf("%lld%lld%lld", &a, &b, &n);
printf("%lld", pow(a, b, n));
return 0;
}