zoukankan      html  css  js  c++  java
  • Luogu P3811 [模板]乘法逆元 题解报告

    题目传送门

    【题目大意】

    给定$n$,求$1~n$在膜$p$意义下的乘法逆元。

    【思路分析】

    好的原本我只会求单个数的逆元,然后被告知了这道题之后发现自己不会做(我果然还是太弱了),于是就学了一下递推求逆元。

    设$p=k*i+r$,则可得$k*i+requiv0(mod p)$,然后乘上$i^{-1},r^{-1}$即可得到$k*r^{-1}+i^{-1}equiv0(mod p)$

    由于$k=lfloor frac{p}{i} floor,r=p mod i$,所以$i^{-1}equiv -lfloor frac{p}{i} floor*(p mod i)(mod p)$

    于是我们就得到递推式啦!QwQ

    $$inv[i]=(-p/i*inv[p mod i]+p)mod p$$

    【代码实现】

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<cstring>
     4 #include<algorithm>
     5 #include<cmath>
     6 #include<queue>
     7 #define g() getchar()
     8 #define rg register
     9 #define go(i,a,b) for(rg int i=a;i<=b;i++)
    10 #define back(i,a,b) for(rg int i=a;i>=b;i--)
    11 #define db double
    12 #define ll long long
    13 #define il inline
    14 #define pf printf
    15 #define mem(a,b) memset(a,b,sizeof(a))
    16 using namespace std;
    17 int fr(){
    18     int w=0,q=1;
    19     char ch=g();
    20     while(ch<'0'||ch>'9'){
    21         if(ch=='-') q=-1;
    22         ch=g();
    23     }
    24     while(ch>='0'&&ch<='9') w=(w<<1)+(w<<3)+ch-'0',ch=g();
    25     return w*q;
    26 }
    27 const int N=3e6+2;
    28 int n,p;
    29 ll inv[N];
    30 int main(){
    31     //freopen("","r",stdin);
    32     //freopen("","w",stdout);
    33     n=fr();p=fr();
    34     inv[1]=1;pf("%lld
    ",inv[1]);
    35     go(i,2,n) inv[i]=(p-p/i)*inv[p%i]%p,pf("%lld
    ",inv[i]);
    36     return 0;
    37 }
    代码戳这里
  • 相关阅读:
    hdu2328 Corporate Identity
    hdu1238 Substrings
    hdu4300 Clairewd’s message
    hdu3336 Count the string
    hdu2597 Simpsons’ Hidden Talents
    poj3080 Blue Jeans
    poj2752 Seek the Name, Seek the Fame
    poj2406 Power Strings
    hust1010 The Minimum Length
    hdu1358 Period
  • 原文地址:https://www.cnblogs.com/THWZF/p/11569174.html
Copyright © 2011-2022 走看看