題意:給出A,B兩個整數(0 <= A,B <= 50000000),輸出A^B(A的B次,不是異或)的所有因子和模9901;
Sample Input
2 3
Sample Output
15
Hint
The natural divisors of 8 are: 1,2,4,8. Their sum is 15.
15 modulo 9901 is 15 (that should be output).
思路:首先,一個數的因子和是他的所有質因數的最大次方的因此和的乘積。(例如12的因子和是1+2+3+4+6+12=1+2+3+2*2+2*3+2*2*3=(1+2+2*2)*(1+3)=28)。然後,算出所有的質因數和質因數的個數,然後,算出(1+a+a*a+..),我使用等比數列求和公式算的。
等比數列求和公式,我按首項爲一來算,1*(1-q^n)/(1-q);
之前每步都要%9901,因爲等比數列求和公式有除法,涉及到求逆元運算,用擴展歐幾裏和定理算出逆元。
擴展歐幾裏和定理:若c%gcd(a,b)==0,則a*x+b*y=c,xy有解。
求逆元:使a/b%p==a*c%p; 則b*c%p==1。-->b*c=1+k*p;-->b*c-k*p=1;然後用擴展歐幾裏何定裏求出c,c便是逆元。
還有別的方法求逆元,待補充(心情好時來補充。)
用逆元算的話,要考慮除數是9901的倍數的問題,因爲除數是a-1,a%9901==1,這種情況直接展開,答案是(1+a+a*a+a*a*a)%9901,共n+1項,答案是(n+1);
代碼:
#include<cstdio> #include<cmath> #include<cstring> #include<queue> #include<stack> #include<cstdlib> #include<iomanip> #include<string> #include<vector> #include<map> #include<string> #include<iostream> #include<algorithm> using namespace std; #define INF 0x3f3f3f3f typedef long long ll; #define Max(a,b) (a>b)?a:b #define lowbit(x) x&(-x) ll pow1(ll a,ll b)//二分快速冪 { ll ans=1,k=a; while(b) { if(b%2) ans*=k,ans%=9901; k*=k; k%=9901; b/=2; } return ans; } ll exgcd(ll a,ll b,ll &x,ll &y) { if(b==0) { x=1;y=0; return a; } ll r=exgcd(b,a%b,x,y); ll t=x;x=y;y=t-a/b*y; return r; } ll work(ll a,ll b,ll x,ll y) { if(a>1&&(a-1)%9901==0) { return (b+1)%9901; } b++; b%=9900;//這邊我用費馬小定理優化了一下,如果a,p互質,則(a^(p-1))%p=1; b=pow1(a,b); b=(b-1+9901)%9901; a=exgcd(a-1,9901,x,y);//x就是a-1的逆元。 x%=9901; x=(x+9901)%9901; b*=x; b%=9901; return b; } int main() { ll a,b,x,y,sum=1,xx=0,n; scanf("%lld%lld",&a,&b); //求質因數及個數 n=a; for(int i=2;i*i<=a;i++) { xx=0; while(n%i==0) { n/=i; xx++; } if(xx) sum*=work(i,xx*b,x,y);//求(1+i*i+i*i*i+...)(xx項) sum%=9901; } if(n!=1)//避免因數是質數並且該因數平方>a的情況,例如28*31 { sum*=work(n,b,x,y); sum%=9901; } if(a==0) sum=0; printf("%lld\n",sum); }
還可以用矩陣快速冪來求(1+a+a*a+..),還有用二分遞歸來求的,待補充。(心情好時再寫。)