"Hdu6608" Fansblog Wilson's Theorem

「hdu6608」 Fansblog

Prior to look back now more than school league title: Fansblog, found an interesting thing, 快速积the time complexity than the average *much faster, just has been Tlein general use *, it can also be raped T.

快速积 >> * 速度的原因:
Here Insert Picture Description
Wilson's Theorem:

  • Wilson's Theorem is positive for any prime number K has:
    (! (. 1-K)) = K-K. 1%

Solution: inverse + Wilson's Theorem

  • First, we use an ordinary prime number sieve, the largest prime number less than p
  • Then push conducive to Wilson's Theorem:
 ((p−1)!)%p=q!×(q+1)×(q+2)×...×(p−1)%p=(p−1||
       得    V
 q!(1/((q+1)*(q+2)..... *(p-2)))(mod p)       
  • Then use inverse, seeking: ! Q (P MOD)

AC Code:

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(long long i=(a);i<=(b);i++)
#define ll long long
ll ksc(ll a,ll b,ll mod)
{
    ll res=0;
    while(b)
    {
        if(b&1)
            res=res+a%mod;
        a=a+a%mod;
        b>>=1;
    }
    return res%mod;
}
ll ksm(ll a,ll b,ll mod)
{
    ll res=1;
    while(b)
    {
        if(b&1)
            res=ksc(res,a,mod);
        a=ksc(a,a,mod);
        b>>=1;
    }
    return res%mod;
}
bool shai(ll x)
{
    for(ll i=2;i<=sqrt(x);i++)
    {
        if(x%i==0)
            return false;
    }
    return true;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll t;
    cin>>t;
    while(t--)
    {
        ll p;
        cin>>p;
        ll q=p;
        while(q--)
        {
            if(shai(q))
                break;
        }
        ll res=1;
        rep(i,q+1,p-2)
        {
            res=ksc(res,ksm(i,p-2,p),p);
        }
        cout<<res<<endl;
    }
}	
Published 222 original articles · won praise 16 · views 9721

Guess you like

Origin blog.csdn.net/yangzijiangac/article/details/104383316