快速幂算法题目描述
给你三个整数 a,b,pa,b,p,求 a^b mod p。
输入格式
输入只有一行三个整数,分别代表 a,b,p。
输出格式
输出一行一个字符串 a^b mod p=s,其中 a,b,p 分别为题目给定的值, s 为运算结果。
输入输出样例
输入 #1复制
2 10 9
输出 #1复制
2^10 mod 9=7
说明/提示
样例解释
2^10=1024,1024mod9=7。
数据规模与约定对于100% 的数据,保证 0≤a,b<2^ 31 a+b>0,2≤p<2^31
a ^ n +a ^ m =a ^ m+n
a^n有两种情况,一种是n为偶数,一种是n为奇数
举个例子:
当要求3^100 0000次方的时候,2 ^ 1 = 2,2 ^ 2 = 4,…2 ^ 20 =1048576;
所以我们最多执行20次就够了
#include#include #include #include #include #include #include #include #include #include
using namespace std; typedef long long ull; ull a,b,p; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin>>a>>b>>p; ull x=1,bb=b,aa=a; while(b>0) { if(b%2==1)//如果是奇数就多乘一次 { x *= a; x %= p; } a*=a; a%=p; b=b/2;最后一定会变成 1 } ull y=x%p; cout< 继续普及python: pow函数:pow(a,b,c) == a**b%c
ps:必须要用这个函数,自己手写不行,会超时import math a=input().split() print(f'{a[0]}^{a[1]} mod {a[2]}={pow(int(a[0]),int(a[1]),int(a[2]))}')二进制 64位整数乘法求 a 乘 b 对 p 取模的值。
输入格式
第一行输入整数a,第二行输入整数b,第三行输入整数p。
输出格式
输出一个整数,表示a*b mod p的值。
数据范围
1≤a,b,p≤1018这已经超过了 long long 的最大范围了
所以把 b写成二进制形式,然后如果某位上为1就加上它a*(2^n)次方,并且每次计算后取模就可以例:计算 3 ^ 7
7的二进制 111
3*(2^0)=3
3*(2^1)=6
3*(2^2)=12# includeusing namespace std; typedef long long ll; ll n,a,p,b,x; int main() { cin>>a>>b>>p; x=0; while(b>0) { if(b&1) { x=(x+a)%p; } a=a*2%p; b>>=1; } cout<



