题目链接:
gcd
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 131072/131072 K (Java/Others)
Problem Description
Little White learned the greatest common divisor, so she plan to solve a problem: given x, n,
query ∑gcd(xa−1,xb−1) (1≤a,b≤n)
query ∑gcd(xa−1,xb−1) (1≤a,b≤n)
Input
The first line of input is an integer T ( 1≤T≤300)
For each test case ,the single line contains two integers x and n ( 1≤x,n≤1000000)
For each test case ,the single line contains two integers x and n ( 1≤x,n≤1000000)
Output
For each testcase, output a line, the answer mod 1000000007
Sample Input
5
3 1
4 2
8 7
10 5
10 8
Sample Output
2
24
2398375
111465
111134466
题意:
求这个式子的值;
思路:
完全懵逼;看了题解才知道gcd(xa-1,xb-1)=xgcd(a,b)-1;好像以前在哪看过这个式子;
然后就变成了喜闻乐见的求和式子了.∑∑xgcd(a,b)-1;跟欧拉函数联系起来啦num[i]={gcd(a,b)==i的对数1<=a,b<=n}={gcd(a,b)==1的对数1<=a,b<=n/i}
欧拉函数啊;num[i]=2*{phi[1]+phi[2]+...+phi[n/i]}-1;这就是求∑num[i]*(xi-1)的和;再遍历一遍求答案还会超时;题解说要按n/i的值分成等比数列再求;就像那个约瑟夫变形问题按商分成求等差数列和一样;那就分层求好了,快速幂求逆,注意x==1的情况,最最重要的是要得到第一个那个公式;
AC代码:
/************************************************ ┆ ┏┓ ┏┓ ┆ ┆┏┛┻━━━┛┻┓ ┆ ┆┃ ┃ ┆ ┆┃ ━ ┃ ┆ ┆┃ ┳┛ ┗┳ ┃ ┆ ┆┃ ┃ ┆ ┆┃ ┻ ┃ ┆ ┆┗━┓ ┏━┛ ┆ ┆ ┃ ┃ ┆ ┆ ┃ ┗━━━┓ ┆ ┆ ┃ AC代马 ┣┓┆ ┆ ┃ ┏┛┆ ┆ ┗┓┓┏━┳┓┏┛ ┆ ┆ ┃┫┫ ┃┫┫ ┆ ┆ ┗┻┛ ┗┻┛ ┆ ************************************************ */ #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <bits/stdc++.h> #include <stack> using namespace std; #define For(i,j,n) for(int i=j;i<=n;i++) #define mst(ss,b) memset(ss,b,sizeof(ss)); typedef long long LL; template<class T> void read(T&num) { char CH; bool F=false; for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar()); for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar()); F && (num=-num); } int stk[70], tp; template<class T> inline void print(T p) { if(!p) { puts("0"); return; } while(p) stk[++ tp] = p%10, p/=10; while(tp) putchar(stk[tp--] + '0'); putchar(' '); } const LL mod=1e9+7; const double PI=acos(-1.0); const LL inf=1e18; const int N=1e6+10; const int maxn=1e5+4; const double eps=1e-8; int phi[N]; LL sum[N]; inline void Init() { phi[1]=1; sum[1]=1; For(i,2,N-1) { if(!phi[i]) { for(int j=i;j<N;j+=i) { if(!phi[j])phi[j]=j; phi[j]=phi[j]/i*(i-1); } } sum[i]=sum[i-1]+phi[i]; } } LL pow_mod(LL x,int y) { LL s=1,base=x; while(y) { if(y&1)s=s*base%mod; base=base*base%mod; y>>=1; } return s; } int main() { Init(); int t,n; LL x; read(t); while(t--) { read(x);read(n); LL ans=0; if(x==1)cout<<"0 "; else { LL temp=pow_mod(x-1,(int)mod-2); int l=1,r; while(l<=n) { r=n/(n/l); LL g=((pow_mod(x,r+1)-pow_mod(x,l)+mod)*temp-(r-l+1)+mod)%mod; ans=(ans+(2*sum[n/l]-1)%mod*g)%mod; l=r+1; } cout<<ans<<" "; } } return 0; }