跳到正文

算法·理论

数论之模运算

how_why约 3 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v2当前
  2. v1

前言

本蒻蒻在学习模运算里的定理时经常因理论知识不足而被难倒,现在特写一篇来整理相关定理及其一些应用。

会随着本蒻蒻学习进度更新。

模意义下的乘法逆元

定义

a/b=a∗b−1( mod p)a / b = a \ast b^{-1} ( \bmod{p} )

a/b∗b∗b−1=1( mod p)a / b \ast b \ast b^{-1}=1 (\bmod{p} )

即 b∗b−1=1( mod p)b \ast b^{-1} = 1 ( \bmod{p})

性质

积性:(a×b)−1=a−1×b−1 (a \times b)^{-1} =a^{−1} \times b^{−1}。

自逆性:(a−1)−1=a(a^{−1}) ^{−1}=a 。

第一种:

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

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

b∗b−1=1=bp−1( mod p)b*b^{-1}=1=b^{p-1} (\bmod 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;
}
原文