"Lucas theorem/Fermat theorem/Chinese remainder theorem/extended Euclid" [Bzoj 1951] Ancient pig text

Source: Internet
Author: User
Tags mul

[Description] Ask

Easy to get,

So, the focus is on how to ask

If P-1 is a prime number, we can enumerate all d with the time of sqrt (n) and calculate the sum by the Lucas theorem respectively.
But we find that p-1=2*3*4679*35617 is not a prime number, so does Lucas ' theorem work? No, we can work out the model of 2, 3, 4679, 35617, and write four congruence equations, then solve them with grandson's theorem. Pay attention to the situation of special g==p, at this time Fermat theorem is not established, ans=0.


#include <cmath>#include <cstdio>typedef Long LONG Ll;constintMod=999911659; ll prime[4]={2,3,4679,35617};ll num[4],inver[4];void EXGCD (LLx, LLy, ll&a,ll&b) {if(!y) a=1, b=0;Else{EXGCD (y,x%y, b,a); B-=a*(x/y); }}ll Pow (ll a,ll N,intP) {ll ans=1; while(n) {if(n&1) Ans=ans*a%p; A=a*a%p; n>>=1; }returnAns;} ll C (LLm, ll N,ll p) {if(m<n)return 0;if(m==n)return 1;if(n>m-N) n=m-N; ll ans=1, cm=1, cn=1; for(LL i=0; i<n;i++) cm=cm*(m-I.)%p, CN=CN*(N-i)%p;returnCm*pow(cn,p-2, p)%p;} ll Lucas (LLm, ll N,ll p) {if(!n)return 1;return(Lucas (m/p,n/p, p)*c(m%pN%p, p))%p;}intGetintN) { for(intI=1, lim=sqrt(n) +1; i<lim;i++)if(! (n%i)){ for(intj=0;j<4; j + +) num[j]= (Num[j]+lucas (N,i,prime[j]))%prime[j];if(I*i-N) for(intj=0;j<4; j + +) num[j]= (Num[j]+lucas (N,n/i,prime[j]))%prime[j]; } ll Mul=1, ans=0; for(intI=0;i<4; i++) Mul*=Prime[i]; for(LL i=0,t;i<4; i++) {EXGCD (mul/prime[i],prime[i],inver[i],t); Inver[i]*=Mul/prime[i]; } for(intI=0;i<4; i++) ans= (Ans+num[i]*inver[i])%(mod-1);return(Ans+ (mod-1))%(mod-1);}intMain () {intN,g; scanf"%d%d", &n,&g);if(mod==g) {printf("0");return 0; } g%=MoDprintf("%lld", Pow (G,get (n), MoD));return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Lucas theorem/Fermat theorem/Chinese remainder theorem/extended Euclid" [Bzoj 1951] Ancient pig text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.