【模板】乘法逆元

17 篇文章 0 订阅

题目链接

题目描述

给定 n, p 求 1 ∼ n 中所有整数在模 p 意义下的乘法逆元。

输入格式

一行两个正整数 n, p。

输出格式

输出 n 行,第 i 行表示 i 在模 p 下的乘法逆元。

输入输出样例

输入

10 13

输出

1
7
9
10
8
11
2
5
3
4

方法一:递推法

#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e6 +5;
typedef long long ll;
ll inv[maxn];

int main()
{
	inv[0] = 0, inv[1] = 1;
	int n, p;
	scanf("%d %d", &n, &p);
	printf("1\n");
	for(int i = 2; i <= n; i++){
		inv[i] = (ll)p - (p / i) * inv[p % i] % p;
		printf("%lld\n", inv[i]);
	}
	return 0;
}

方法二:阶乘逆元法

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 3e6 + 10;
ll n, p, c[maxn], f[maxn];

inline ll quickpow(ll a, ll b)
{
	ll res = 1;
	a %= p;
	while(b){
		if(b & 1)
			res = (res * a) % p;
		b >>= 1;
		a = (a * a) % p;
	}
	return res % p;
}

int main()
{
	scanf("%d %d", &n, &p);
	c[0] = 1;
	for(int i = 1; i <= n; i++)
		c[i] = (c[i - 1] * i) % p;
	f[n] = quickpow(c[n], p - 2);
	for(int i = n - 1; i >= 1; i--)		// 递推阶乘的逆元 
		f[i] = (f[i + 1] * (i + 1)) % p;
	for(int i = 1; i <= n; i++)
		printf("%lld\n", (f[i] * c[i - 1]) % p);
	return 0;
}

方法三:扩展欧几里得

#include<cstdio>
using namespace std;

inline int read() 
{
	register int a = getchar(), b = 0;
	while (a > '9' || a < '0')
		a = std::getchar();
	while (a>='0' && a<='9')
	{
		b = b * 10 + a - '0';
		a = std::getchar();
	}
	return b;
}

inline void exgcd(int a, int b, int &x, int &y)
{
	if(b == 0){
		x = 1;
		y = 0;
		return ;
	}
	exgcd(b, a % b, x, y);
	int t = y;
	y = x - a / b * y;
	x = t;
	return ;
}

inline void write(int &x)
{
	register int f[16], i = 0;
	while (x>0)
	{
		++i;
		f[i] = x % 10 + '0';
		x = x / 10;
	}
	while (i > 0)
	{
		std::putchar(f[i]);
		--i;
	}
	std::putchar('\n');
}

int main()
{
	register int i, x, y;
	const int n = read(), p = read();
	for(i = 1; i <= n; i++){
		exgcd(i, p, x, y);
		while (x > p)
			x = x - p;
		while (x < 0)
			x = x + p;
		write(x);
	}
	return 0;
}

方法四:费马小定理求逆元

这道题会被卡,就不放代码了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值