题解
2025-08-05 14:31:44
发布于:上海
29阅读
0回复
0点赞
逆元的概念:(a和p必须互素)
如果b是a的逆元:(a * b) % p =1
例子 :a=3,p=7,a的逆元=5 (因为(3*5)%7=1)
具体计算:
- 3的7-2次方=243
- 243%7=5
费马小定理:a的p-1次方=1 % p
根据此定理可以推出
公式:a的p-2次方%p=a的逆元
#include<iostream>
using namespace std;
typedef long long ll;
ll n,p;
ll f(ll a,ll b){
ll cheng=a,ans=1,t=b;
while(t){
if(t%2==1)ans*=cheng;
ans%=p;
cheng=cheng*cheng%p;
t/=2;
}
return ans%p;//利用快速幂求a的p-2次方并根据公式%p
}
int main(){
cin>>n>>p;
for(ll i=1;i<=n;i++)
cout<<f(i,p-2)<<" ";
return 0;
}
建议官方改成最小逆元,到后面逆元就有无穷个了
这里空空如也
有帮助,赞一个