E - Sum of gcd of Tuples (Hard)
Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 500 points
PS:这类%mod的题似乎是只要超出mod都可以%mod,由题意知如果一个个算肯定会超时,所以要从结果为k的gcd的个数切入,另外注意mod的使用,如果答案已为负数记得加一个mod。
Problem Statement
Consider sequences {A1,...,AN} of length NN consisting of integers between 1 and K (inclusive).
There are K^N such sequences. Find the sum of gcd(A1,...,AN) over all of them.
Since this sum can be enormous, print the value modulo (109+7) .
Here gcd(A1,...,AN) denotes the greatest common divisor of A1,...,AN .
Constraints
- 2≤N≤105
- 1≤K≤105
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
NK
Output
Print the sum of gcd(A1,...,AN)over all KN sequences, modulo (109+7) .
Sample Input 1 Copy
3 2
Sample Output 1 Copy
9
gcd(1,1,1)+gcd(1,1,2)+gcd(1,2,1)+gcd(1,2,2)+gcd(2,1,1)+gcd(2,1,2)+gcd(2,2,1)+gcd(2,2,2) =1+1+1+1+1+1+1+2=9
Thus, the answer is 9 .
Sample Input 2 Copy
3 200
Sample Output 2 Copy
10813692
Sample Input 3 Copy
100000 100000
Sample Output 3 Copy
742202979
Be sure to print the sum modulo (109+7).
#include <bits/stdc++.h> using namespace std; #define ll long long const int mod=1e9+7; const int N=1e5+5; ll cnt[N]; ll n,k,ans; ll pow(ll num){ ll res=1,m=n; while(m>0){ if(m&1) res=res*num%mod; num=num*num%mod; m>>=1; } //cout<<res<<'.'<<endl; return res; } int main(){ ios::sync_with_stdio(0); cin>>n>>k; for(ll i=k;i>=1;i--){ cnt[i]=pow(k/i); for(ll j=2;j*i<=k;j++){ cnt[i]-=cnt[j*i]; } ans+=(mod+(cnt[i]*i)%mod)%mod; ans=(ans+mod)%mod; //cout<<ans<<endl; } cout<<ans<<endl; return 0; }
浙公网安备 33010602011771号