zoukankan      html  css  js  c++  java
  • 线性求逆元 P3811 【模板】乘法逆元 题解

    题目大意

    (1-N) 的逆元,要求 (O(n))

    P3811 【模板】乘法逆元

    问题求解

    大致的推导是这个样子

    我们设

    [p=k imes i +r ]

    [Rightarrow k imes i+requiv0(mod p) ]

    两边除去(i^{-1} imes r^{-1}(mod p)),就变成

    [Rightarrow k imes r^{-1}+i^{-1}equiv0(mod p) ]

    移项

    [Rightarrow i^{-1} equiv -k imes r^{-1} ]

    由于 (p=k imes i +r) 可知

    [k=p/i,r=p\% i ]

    代入

    [Rightarrow i^{-1} equiv -p/i imes (p\% i)^{-1} ]

    由于(C++)中摸的性质,可能会出负数,我们将两边都加上(p)

    [Rightarrow i^{-1} equiv (p-p/i) imes (p\% i)^{-1} ]

    [Rightarrow i^{-1} = (p-p/i) imes (p\% i)^{-1}\%p ]

    (inv[i])来代表逆元,所以

    [Rightarrow inv[i]=(p-p/i) imes inv[p\%i] \%p ]

    就可以线性求逆元了

    当然如果你觉得上面的东西很难记住,就可以使用下面的方法

    地球人都知道怎么推(n!^{-1})

    所以

    [n^{-1}=n! imes (n+1)!^{-1} ]

    代码实现

    #pragma GCC optimize(2)
    #include<bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const int maxn=3e6+5;
    int N,a[maxn],p;
    LL inv[maxn];
    struct IO{
        static const int S=1<<21;
        char buf[S],*p1,*p2;int st[105],Top;
        ~IO(){clear();}
        inline void clear(){fwrite(buf,1,Top,stdout);Top=0;}
        inline void pc(const char c){Top==S&&(clear(),0);buf[Top++]=c;}
        inline char gc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;}
        inline IO&operator >> (char&x){while(x=gc(),x==' '||x=='
    '||x=='r');return *this;}
        template<typename T>inline IO&operator >> (T&x){
            x=0;bool f=0;char ch=gc();
            while(ch<'0'||ch>'9'){if(ch=='-') f^=1;ch=gc();}
            while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=gc();
            f?x=-x:0;return *this;
        }
        inline IO&operator << (const char c){pc(c);return *this;}
        template<typename T>inline IO&operator << (T x){
            if(x<0) pc('-'),x=-x;
            do{st[++st[0]]=x%10,x/=10;}while(x);
            while(st[0]) pc('0'+st[st[0]--]);pc('
    ');
    		return *this;
        }
    }fin,fout;
    int main(){
    	freopen("P3811.in","r",stdin);
    	freopen("P3811.out","w",stdout);
    	fin>>N>>p;
    	inv[1]=1;fout<<inv[1];
    	for(int i=2;i<=N;i++)inv[i]=inv[p%i]*(p-p/i)%p,fout<<inv[i];
    	return 0;
    }
    
  • 相关阅读:
    javaScirpt学习之事件
    验证表单内容之后如何阻止表单提交
    利用js制作异步验证ajax方法()
    Ajax制作无刷新评论系统
    ajax查询数据的举例
    以Ajax的方式访问数据库
    jquery中的全局事件
    jquery序列化元素
    jquery中的ajax
    jquery与ajax的应用
  • 原文地址:https://www.cnblogs.com/martian148/p/15193926.html
Copyright © 2011-2022 走看看