数论之模运算
前言
本蒻蒻在学习模运算里的定理时经常因理论知识不足而被难倒,现在特写一篇来整理相关定理及其一些应用。
会随着本蒻蒻学习进度更新。
模意义下的乘法逆元
定义
即
性质
积性:
自逆性:
第一种:
当
快速幂可以解决
#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;
}
第二种
利用扩展欧几里得算法
#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;
}