百度之星2016資格賽 1001代數取模/逆元/費馬小定理


乘法逆元模板題
Ps:費馬小定理解決(也可以用擴展歐幾里得算法)
逆元 :(a/b) (mod N) = (a * x) (mod N)。 x表示b的逆元。並且 b*x ≡ 1 (mod N )  注意:只有當b與N互質的時候才存在逆元。一般情況下,ax+by=1;得 x爲a mod  b 的逆元,y爲 b mod a的逆元。

根據費馬小定理,對於素數n,任意不是n的倍數的b,都有:   b^(N-1)=1(mod N)

於是可以拆成: b*b^(N-2)=1(mod N)        --------> a/b=a/b*(b*b^(N-2))=a*(b^(n-2))(mod N)

也就是我們要求的逆元爲b^(N-2)(mod N)
#include<iostream>
#include<stdio.h>
#define LL long long
#define mo 9973
using namespace std;
LL qmod(LL a,LL b)
{
    LL sum=1;
    while(b)
    {
        if(b&1) sum=(sum*a)%mo;
        b>>=1;
        a=(a*a)%mo; 
    }
    return sum;
}
int main()
{
    int n,i,a,b;
    string str;
    LL s[100005];
    while(scanf("%d",&n)!=EOF)
    {
        cin>>str;
        s[0]=1;
        for(long i=1;i<=str.length();i++)
           s[i]=(s[i-1])*(str[i-1]-28)% mo;
        for(int i=0;i<n;i++)
        {
            scanf("%d%d",&a,&b);
            if(a>b) swap(a,b);
            printf("%ld\n",(s[b]*(qmod(s[a-1],mo-2)%mo))%mo);
        }
    }
    return 0; 
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章