Multiplicative inverse template

Number of single O (logmod) inversing

$View$ $Code$
  
  
   
   
const int mod=998244353;
inline long long qpow(long long a,long long b)
{
    long long ans=1;
    while(b)
    {
        if(b&1)
            ans=ans*a%mod;
        a=a*a%mod;
        b/=2;
    }
    return ans%mod;
}
long long calcinv(long long x)
{
    return qpow(x,mod-2);
}

  
  

O (n) to find the inverse element 1 ~ n (linear inverse element)

\(View\) \(Code\)

#include<bits/stdc++.h>
using namespace std;
inline int read()
{
    int ret=0,f=1;
    char ch=getchar();
    while('9'<ch||ch<'0')
    {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while('0'<=ch&&ch<='9')
    {
        ret=(ret<<1)+(ret<<3)+ch-'0';
        ch=getchar();
    }
    return ret*f;
}
int n,p;
long long inv[3000005];
int main()
{
    n=read();
    p=read();
    inv[1]=1;
    for(register int i=2;i<=n;i++)
        inv[i]=1ll*(p-p/i)*inv[p%i]%p;
    for(register int i=1;i<=n;i++)
        printf("%lld\n",inv[i]);
    return 0;
}

O (n) 1 to find the inverse element n factorial (factorial inverse element)

$View$ $Code$
  
  
   
   
const int mod=998244353;
int maxn;
long long ans,fac[100005],inv[100005];
inline void pre()
{
    fac[1]=1;
    inv[0]=1;
    for(register int i=2;i<=maxn;i++)
    {
        fac[i]=fac[i-1]*i%mod;
    }
    inv[maxn]=qpow(fac[maxn],mod-2,mod);
    for(register int i=maxn;i;i--)
    {
        inv[i-1]=inv[i]*i%mod;
    }
}

  
  

Guess you like

Origin www.cnblogs.com/Peter0701/p/11869760.html