给出3个正整数A B C,求A^B Mod C。
例如,3 5 8,3^5 Mod 8 = 3。
Input
3个正整数A B C,中间用空格分隔。(1 <= A,B,C <= 10^9)
Output
输出计算结果
Input示例
3 5 8
Output示例
3
用到了快速幂 ,挑战P123
比如x ^22 = x ^16 *x ^4*x ^2;
22 转换成二进制是10110;
#include <iostream> using namespace std; typedef long long ll; ll pow_mod(ll x,ll n,ll mod) { ll res = 1; while ( n > 0) { if(n & 1) res = res * x % mod; x = x * x % mod; n >>= 1; //cout<< n << endl; } return res; } int main() { int x,n,mod; cin >> x >> n >> mod; cout<<pow_mod(x,n,mod)<<endl; return 0; }
下面是递归版本
如果n为 偶数 那么 x^n = (x^2) ^ (n/2) n为奇数 无非多乘一个n
#include <iostream> using namespace std; typedef long long ll; ll pow_mod1(ll x,ll n,ll mod) { ll res = 1; if(n == 0) return 1; res = pow_mod1(x * x % mod, n/2,mod); if(n % 2) res = res * x % mod; return res; } int main() { int x,n,mod; cin >> x >> n >> mod; cout<<pow_mod1(x,n,mod)<<endl; return 0; }