AtCoder ABC 162 E - Sum of gcd of Tuples (Hard)(思维)

题目链接:https://atcoder.jp/contests/abc162/tasks/abc162_e

题意:给你两个正整数 n , k n,k n,k,问你 ∑ a [ i ] = 1 k g c d ( a [ 1 ] , a [ 2 ] , . . . , a [ n ] ) % ( 1 e 9 + 7 ) \sum_{a[i]=1}^{k} gcd(a[1],a[2],...,a[n])\%(1e9+7) a[i]=1kgcd(a[1],a[2],...,a[n])%(1e9+7)

思路:首先这一题 n , k n,k n,k的取值范围都是 1 e 5 1e5 1e5,所以暴力肯定是不行的。那我们就可以考虑一下, g c d ( a [ 1 ] , a [ 2 ] , . . . , a [ n ] ) gcd(a[1],a[2],...,a[n]) gcd(a[1],a[2],...,a[n])的值只有可能是 [ 1 , k ] [1,k] [1,k]!!!那我们就可以想办法找出 g c d ( a [ 1 ] , a [ 2 ] , . . . , a [ n ] ) = i gcd(a[1],a[2],...,a[n]) = i gcd(a[1],a[2],...,a[n])=i的个数存到数组 A N S [ i ] ANS[i] ANS[i]中,那么
∑ i = 1 k i × A N S [ i ] \sum_{i=1}^{k}i\times ANS[i] i=1ki×ANS[i]就是答案啊。
那我没有想到了,在不考虑重复的情况下 g c d ( a [ 1 ] , a [ 2 ] , . . . , a [ n ] ) = i gcd(a[1],a[2],...,a[n]) = i gcd(a[1],a[2],...,a[n])=i的个数就是 ( k / i ) n (k/i)^n (k/i)n
那如果考虑重复呢?那就有以下等式:
g c d ( 1 ) = g c d ( 1 ) − g c d ( 2 ) − g c d ( 3 ) − . . . gcd(1) = gcd(1) - gcd(2) - gcd(3) - ... gcd(1)=gcd(1)gcd(2)gcd(3)...
g c d ( 2 ) = g c d ( 2 ) − g c d ( 4 ) − g c d ( 6 ) − . . . gcd(2) = gcd(2) - gcd(4) - gcd(6) - ... gcd(2)=gcd(2)gcd(4)gcd(6)...
g c d ( 3 ) = g c d ( 3 ) − g c d ( 6 ) − g c d ( 9 ) − . . . gcd(3) = gcd(3) - gcd(6) - gcd(9) - ... gcd(3)=gcd(3)gcd(6)gcd(9)...
所以为了代码写起来简单点,我们可以从 k k k开是往后遍历,那么这一题就结束啦。

AC代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

#define LL long long
#define pii pair
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define pd(x) printf("%d\n",x)
#define plld(x) printf("%lld\n",x)
#define rep(i,a,b) for(int i = (a) ; i <= (b) ; i++)
#define per(i,a,b) for(int i = (a) ; i >= (b) ; i--)
#define mem(a) memset(a,0,sizeof(a))
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
#define fast_io ios::sync_with_stdio(false)

const int INF = 1e9;
const LL mod = 1e9 + 7;
const int maxn = 1e5 + 7;

LL qpow(LL a,LL b) {
    LL res = 1;
    while(b) {
        if(b&1) res = (res * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res;
}

int ANS[maxn];

int main() {
    int n,k;
    while(~scanf("%d%d",&n,&k)) {
        mem(ANS);
        per(i,k,1) {
            ANS[i] = qpow(k/i,n);
            LL res = 0;
            for(int j = i + i ; j <= k ; j += i) {
                res = (res + ANS[j]) % mod;
            }
            ANS[i] = (ANS[i] - res + mod) % mod;
        }
        LL ans = 0;
        rep(i,1,k) {
            ans = (ans % mod + ((i % mod) * (ANS[i] % mod)) % mod) % mod;
        }
        plld(ans);
    }
    return 0;
}

你可能感兴趣的:(思维)