ABC 162 E - Sum of gcd of Tuples (Hard)
愚直にやると$ K^N個すべてしらべることになるので、なにかしらの工夫を考える。ここで$ gcd(A_1, A_2, \ldots, A_N)の最大公約数が$ xになるような$ \{A_1, A_2, \ldots, A_N\}の組の数が$ f(x)で求められたとしよう。すると、求める答えは$ \sum_x xf(x)となる。
$ f(x)は単純に考えると$ \lfloor\dfrac{K}{x}\rfloor^Nで求まりそうだが、最大公約数が$ xになる必要があるので、最大公約数が$ 2x, 3x, \ldotsとなるようなものについては除く必要がある。以上から$ f(x) = \lfloor\dfrac{K}{x}\rfloor^N - \sum_{i=2}^{\lfloor\frac{K}{x}\rfloor} f(ix)で$ f(x)が計算できる。これは$ xを$ Kから降順に計算していけば以前の計算結果が利用できる。なお計算量は$ O(K\log K)となる。
code:java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long M = 1_000_000_007;
int N = scanner.nextInt();
int K = scanner.nextInt();
long res = 0;
long[] count = new longK + 1; for (int x = K; x >= 1; x--) {
int n = K / x;
countx = modpow(n, N, M); for (int i = 2; i * x <= K; i++) {
if (countx < 0) countx += M; }
res %= M;
}
System.out.println(res);
}
private static long modpow(long a, long n, long mod) {
long res = 1;
while (n > 0) {
if (n % 2 == 1) res = (res * a) % mod;
a = (a * a) % mod;
n >>= 1;
}
return res % mod;
}
}