模板--逆元求法--LibreOJ--110

这是一道模板题。

给定正整数 nn 与 pp,求 1∼n1∼n 中的所有数在模 pp 意义下的乘法逆元。

Input

一行两个正整数 nn 与 pp

Output

nn 行,第 ii 行一个正整数,表示 ii 在模 pp 意义下的乘法逆元。

样例输入
10 13
样例输出
1
7
9
10
8
11
2
5
3
4

思路一:费马小定理;

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL;
LL n,p;
LL pow_mod(LL x,LL n,LL mod){
	LL res=1;
	while(n){
		if(n&1)	res=res*x%mod;
		x=x*x%mod;
		n=n>>1;
	}
	return res;
}
int main(){
	scanf("%lld%lld",&n,&p);
	for(LL i=1;i<=n;i++)
		printf("%lld\n",pow_mod(i,p-2,p));
	return 0;
} 

思路二:递推求逆元;

#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn=3000005;
LL n,p,inv[maxn];
int main(){
	scanf("%lld%lld",&n,&p);
	inv[1]=1;
	for(int i=1;i<=n;i++){
		if(i!=1)inv[i]=(p-p/i)*inv[p%i]%p;
		printf("%lld\n",inv[i]);
	}
	return 0;
} 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值