当前位置:网站首页>快速幂,逆元的求解
快速幂,逆元的求解
2022-08-11 07:49:00 【疯疯癫癫才自由】
875. 快速幂
给定 n
组 ai,bi,pi,对于每组数据,求出 abiimodpi
的值。
输入格式
第一行包含整数 n
。
接下来 n
行,每行包含三个整数 ai,bi,pi
。
输出格式
对于每组数据,输出一个结果,表示 abiimodpi
的值。
每个结果占一行。
数据范围
1≤n≤100000
,
1≤ai,bi,pi≤2×109
输入样例:
2
3 2 5
4 3 9
输出样例:
4
1
1)迭代写法求快速幂
/**
* 1)迭代写法求快速幂
*/
#include <iostream>
using namespace std;
typedef long long LL;
int qmi(int a,int b,int p)
{
int res=1;
while(b)
{
if(b&1)
res=res*(LL)a%p;
b >>=1;
a=(LL)a*a%p;
}
return res;
}
int main()
{
int n;
cin >> n;
while (n -- )
{
int a,b,p;
cin >> a >> b >> p;
cout << qmi(a,b,p) << endl;
}
return 0;
}
2)递归求快速幂
/**
* 2)递归求快速幂
*/
#include <iostream>
using namespace std;
typedef long long LL;
int qmi(int a,int b,int p)
{
if(b==0)
return 1;
if(b&1)
return (LL)a*qmi(a,b-1,p)%p; //注意这里需要强制转换一下,int会溢出
else
{
LL temp=qmi(a,b/2,p);
return temp*temp%p;
}
}
int main()
{
int n;
cin >> n;
while(n--)
{
int a,b,p;
cin >> a >> b >> p;
cout << qmi(a,b,p) << endl;
}
return 0;
}
876. 快速幂求逆元
给定 n
组 ai,pi,其中 pi 是质数,求 ai 模 pi
的乘法逆元,若逆元不存在则输出 impossible
。
注意:请返回在 0∼p−1
之间的逆元。
乘法逆元的定义
若整数 b,m
互质,并且对于任意的整数 a,如果满足 b|a,则存在一个整数 x,使得 a/b≡a×x(modm),则称 x 为 b 的模 m 乘法逆元,记为 b−1(modm)。
b 存在乘法逆元的充要条件是 b 与模数 m 互质。当模数 m 为质数时,bm−2 即为 b
的乘法逆元。
输入格式
第一行包含整数 n
。
接下来 n
行,每行包含一个数组 ai,pi,数据保证 pi
是质数。
输出格式
输出共 n
行,每组数据输出一个结果,每个结果占一行。
若 ai
模 pi
的乘法逆元存在,则输出一个整数,表示逆元,否则输出 impossible
。
数据范围
1≤n≤105
,
1≤ai,pi≤2∗109
输入样例:
3
4 3
8 5
6 3
输出样例:
1
2
impossible
* 假设 a,b,m都是整数,m>1,且ab与1模m同余,则a与b互为模m的逆元。
* 所以当m为质数的时候,a的m-2次方就是a模m的逆元。(费马小定理)。
/**
* 假设 a,b,m都是整数,m>1,且ab与1模m同余,则a与b互为模m的逆元。
* 所以当m为质数的时候,a的m-2次方就是a模m的逆元。(费马小定理)。
*/
#include <iostream>
using namespace std;
typedef long long LL;
int qmi(int a,int b,int p)
{
if(b==0)
return 1;
if(b&1)
return (LL)a*qmi(a,b-1,p)%p; //注意这里需要强制转换一下,int会溢出
else
{
LL temp=qmi(a,b/2,p);
return temp*temp%p;
}
}
int main()
{
int n;
cin >> n;
while (n -- )
{
int a,p;
cin >> a >> p;
if(a%p==0)
cout << "impossible\n";
else
cout << qmi(a,p-2,p) << endl;
}
return 0;
}
边栏推荐
- 1076 Wifi Password (15 points)
- 流式结构化数据计算语言的进化与新选择
- Interaction of Pico neo3 in Unity
- go-grpc TSL authentication solution transport: authentication handshake failed: x509 certificate relies on ... ...
- Keep track of your monthly income and expenses through bookkeeping
- 1.2 - error sources
- Kaldi语音识别工具编译问题记录(踩坑记录)
- 【Day_13 0509】▲跳石板
- 1081 检查密码 (15 分)
- tf中矩阵乘法
猜你喜欢
随机推荐
go 操作MySQL之mysql包
【实战系列】OpenApi设计规范
1003 I want to pass (20 points)
1046 punches (15 points)
Write a resume like this, easy to get the interviewer
go sqlx 包
无服务器+域名也能搭建个人博客?真的,而且很快
查找最新人员工资和上上次人员工资的变动情况
1081 Check Password (15 points)
string类接口介绍及应用
C语言-结构体
Serverless + domain name can also build a personal blog? Really, and soon
Tensorflow中使用tf.argmax返回张量沿指定维度最大值的索引
3.1-分类-概率生成模型
记录一些遇见的bug——Lombok和Mapstruct的冲突导致,A component required a bean of type ‘com.XXX.controller.converter.
Keep track of your monthly income and expenses through bookkeeping
进阶-指针
Pico neo3在Unity中的交互操作
优炫数据库支持多列分区吗?
[C语言] sscanf如何实现sscanf_s?