线性递推
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define re register
using namespace std;
const int maxn = 3000005;
int n;
long long mod;
int p[maxn];
int main(){
scanf("%d%lld",&n,&mod);
printf("%d
",p[1] = 1);
for(re int i = 2 ; i <= n ; ++i) {
p[i] = -mod / i * p[mod % i] % mod;
if(p[i] < 0) p[i] += mod;
printf("%d
",p[i]);
}
return 0;
}
快速幂
#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
ll n,p;
ll ksm (ll a,ll b=p-2){
ll ans=1;
while(b>0){
if(b&1){
ans=ans*a%p;
}
a=a*a%p;
b>>=1;
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin>>n>>p;
for(int i=1;i<=n;i++) {
cout<<ksm(i)<<endl;
}
return 0;
}
拓展欧几里得
#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
ll n,p;
ll x,y;
void exgcd(ll a,ll b,ll &x,ll &y){
if(b==0){
x=1,y=0;
return;
}
exgcd(b,a%b,y,x);
y-=a/b*x;
}
int main(){
ios::sync_with_stdio(false);
cin>>n>>p;
for(int i=1;i<=n;i++){
exgcd(i,p,x,y);
cout<<((x%p)+p)%p<<endl;
}
return 0;
}