题目
https://www.acwing.com/problem/content/description/91/
思路
-
重要公式:
( a + b ) % p = [ ( a % p ) + ( b % p ) ] % p ( a ∗ b ) % p = [ ( a % p ) ∗ ( b % p ) ] % p (a + b) \% p = [(a \% p) + (b \% p)] \% p \\ (a * b) \% p = [(a \% p) * (b \% p)] \% p (a+b)%p=[(a%p)+(b%p)]%p(a∗b)%p=[(a%p)∗(b%p)]%p -
证明
a b % p 把 b 表 示 成 2 进 制 数 , b = 2 x 1 + 2 x 2 + … … ; a b = a 2 x 1 ∗ a 2 x 2 ∗ … … ; a b % p = ( a 2 x 1 ∗ a 2 x 2 ∗ … … ) % p = [ ( a 2 x 1 % p ) ∗ ( a 2 x 2 % p ) ∗ … … ] % p ; a^b\%p \\ 把b表示成2进制数,b = 2^{x_1}+2^{x_2}+……; \\ a^b = a^{2^{x_1}}*a^{2^{x_2}}*……; \\ a^b\%p = (a^{2^{x_1}}*a^{2^{x_2}}*……)\%p = [(a^{2^{x_1}}\%p)*(a^{2^{x_2}}\%p)*……]\%p; ab%p把b表示成2进制数,b=2x1+2x2+……;ab=a2x1∗a2x2∗……;ab%p=(a2x1∗a2x2∗……)%p=[(a2x1%p)∗(a2x2%p)∗……]%p; -
快速幂模板
//a^b int res = 1; while(b) { if(b&1) res = res*a; a = a*a; b >>= 1; }
AC代码
#include <iostream>
using namespace std;
int main(){
int a,b, p;
cin >> a >> b >> p;
int res = 1%p;
while (b){
if (b & 1) res = (long long)res * a % p;
b >>=1;
a = (long long)a * a %p;//这里取模由上述公式证明可得
}
cout <<res ;
return 0;
}