poj-1845 Sumdiv (逆元+費馬小定理+因子和)

分析:與hdu 1452很類似,就不詳細解釋了,詳細解釋

#include<iostream>
#include<cstdio>
#include<cstring>
typedef long long LL;
using namespace std ;

LL m[205][2];
int cnt;
 
void exgcd(LL a,LL b,LL &x,LL &y) 
{
	if(b==0){
		x=1;
		y=0;
		return;
	}
	exgcd(b,a%b,x,y);
	LL t=x-a/b*y;
	x=y;
	y=t;
	return;
}

void eular(LL x)
{
	cnt=0;
	for(LL i=2;i*i<=x;i++){
		if(x%i==0){
			m[cnt][0]=i;
			m[cnt][1]=1;
			x/=i;
			while(x%i==0){
				x/=i;
				m[cnt][1]++;
			}
			cnt++;
		}
	}
	if(x>1){
		m[cnt][0]=x;
		m[cnt++][1]=1;
	}
}

LL get_ans(LL x,LL y)
{
	x%=9901;
	if(x==0) return 9900;  //因爲答案不能爲負數,而輸出的ans-1<0 ,所以借9901-1; 
	if(x==1) return  0;    //ans=1-1; 
	LL ans=1;
	y%=9900;
	while(y){
		if(y&1)ans=(ans*x)%9901;
		y>>=1;
		x=(x*x)%9901;
	}
	return ans-1;
}

int main()
{
    LL a,b,ans;
    LL x,y;
    while(scanf("%lld %lld",&a,&b)!=EOF){
		eular(a);
		ans=1;
		for(int i=0;i<cnt;i++) m[i][1]*=b;
		for(int i=0;i<cnt;i++){
			if(m[i][0]%9901==0) continue;    //它的求餘值爲1。
			if(m[i][0]%9901==1){               //這個很重要,因爲它求逆元不存在,如果不判,答案可能會錯的。
				ans=ans*(m[i][1]+1)%9901;       //這個我糾結了好久,我認爲:p^k/(p-1)%(p-1)=p^(k-1)%(p-1),纔會有這樣的答案。
				continue;
			}
			ans=ans*get_ans(m[i][0],m[i][1]+1)%9901;
			exgcd(m[i][0]-1,9901,x,y);                //求m[i][0]-1關於9901的逆元。 
			x=(x%9901+9901)%9901;
			ans=ans*x%9901;
		}
		printf("%lld\n",ans);
    }
 	return 0 ;
}


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