跳到正文

算法·理论

乘法逆元

how_why约 3 分钟
原文

这是 2025年11月6日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年10月31日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

定义

a/b=a∗b−1′(modp)a/b=a*b^{-1'}(mod p)

a/b∗b∗b−1′=1(modp)a/b*b*b^{-1'}=1 (mod p)

即b∗b−1′=1(modp) 即b*b^{-1'}=1(mod p)

第一种:

当p为质数时,可用费马小定理

若a,p互质,则ap−1=1(modp) 若a,p互质,则a^{p-1}=1 (mod p)

b∗b−1′=1=bp−1(modp)b*b^{-1'}=1=b^{p-1} (mod p)

b−1′=bp−2 b^{-1'}=b^{p-2}

快速幂可以解决

C++
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace  std;

long long n,p;

long long ksm(long long a,long long b){
	long long ans=1;
	a%=p;
	while(b){
		if(b &1) ans=ans*a%p;
		a=a*a%p;
		b>>=1;
	}
	return ans%p;
}

inline int read(){
	int num=0;
	char ch=getchar();
	while(ch>'9'||ch<'0') ch=getchar();
	while(ch<='9'&&ch>='0'){
		num=num*10+ch-'0';
		ch=getchar();
	}
	return num;
}
void write(long long x){
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);putchar(x%10^48);
}

int main(){
	n=read();p=read();
	for(int i=1;i<=n;i++){
		write(ksm(i,p-2));
		putchar('\n');
	}
	return 0;
}

第二种

扩展欧几里得算法 看这里扩展欧几里得

C++
#include<bits/stdc++.h>
using namespace std;

int x,y;

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

inline int read(){
	int num=0;
	char ch=getchar();
	while(ch>'9'||ch<'0') ch=getchar();
	while(ch<='9'&&ch>='0'){
		num=num*10+ch-'0';
		ch=getchar();
	}
	return num;
}
void write(long long x){
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);putchar(x%10^48);
}

int main(){
	int n,p;
	n=read();p=read();
	for(int i=1;i<=n;i++){
		exgcd(i,p);
		write((x%p+p)%p);
		putchar('\n');
	}
	return 0;
}