Description
Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,C<=1000000000,1<=B<=10^1000000).
Input
Output
Sample Input
3 2 4 2 10 1000
Sample Output
1
24
高次幂取模,套公式搞定。
(B>=phi(C))
#include<set>
#include<map>
#include<ctime>
#include<cmath>
#include<stack>
#include<queue>
#include<bitset>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define rep(i,j,k) for (int i = j; i <= k; i++)
#define per(i,j,k) for (int i = j; i >= k; i--)
#define loop(i,j,k) for (int i = j;i != -1; i = k[i])
#define lson x << 1, l, mid
#define rson x << 1 | 1, mid + 1, r
#define ff first
#define ss second
#define mp(i,j) make_pair(i,j)
#define pb push_back
#define pii pair<int,LL>
#define in(x) scanf("%d", &x);
using namespace std;
typedef long long LL;
const int low(int x) { return x&-x; }
const double eps = 1e-4;
const int INF = 0x7FFFFFFF;
const int mod = 1e9 + 7;
const int N = 1e6 + 10;
LL n, m, x;
char s[N];
LL phi(LL x)
{
LL res = 1;
for (LL i = 2; i*i <= x; i++)
{
if (x%i) continue;
res *= i - 1;
for (x /= i; !(x%i); res *= i, x /= i);
}
return res * max(x - 1, 1LL);
}
void get()
{
if (strlen(s) <= 10) { sscanf(s, "%lld", &x); return; }
LL g = phi(m);
x = 0;
for (int i = 0; s[i]; i++) x = (x * 10 + s[i] - '0') % g;
x = x + g;
}
int main()
{
while (scanf("%lld%s%lld", &n, s, &m) != EOF)
{
LL ans = 1; get();
for (; x; x >>= 1)
{
if (x & 1) (ans *= n) %= m;
(n *= n) %= m;
}
printf("%lld\n", ans % m);
}
return 0;
}
也可以直接用十进制快速幂,效率稍低
#include<set>
#include<map>
#include<ctime>
#include<cmath>
#include<stack>
#include<queue>
#include<bitset>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define rep(i,j,k) for (int i = j; i <= k; i++)
#define per(i,j,k) for (int i = j; i >= k; i--)
#define loop(i,j,k) for (int i = j;i != -1; i = k[i])
#define lson x << 1, l, mid
#define rson x << 1 | 1, mid + 1, r
#define ff first
#define ss second
#define mp(i,j) make_pair(i,j)
#define pb push_back
#define pii pair<int,LL>
#define inone(x) scanf("%d", &x);
#define intwo(x,y) scanf("%d%d", &x, &y);
using namespace std;
typedef unsigned long long LL;
const int low(int x) { return x&-x; }
const double eps = 1e-4;
const int INF = 0x7FFFFFFF;
const int mod = 1e9 + 7;
const int N = 1e6 + 10;
int n, m;
char s[N];
int main()
{
while (scanf("%d%s%d", &n, s, &m) != EOF)
{
int ans = 1;
per(i, strlen(s) - 1, 0)
{
int res = n;
rep(j, 1, 9)
{
if (s[i] - '0' == j) ans = 1LL * ans * res % m;
res = 1LL * res * n % m;
}
n = res;
}
printf("%d\n", ans);
}
return 0;
}