只不过要求逆元。
1 #include<cstdio> 2 typedef long long LL; 3 #define MOD 1000000007 4 LL PowMod(LL a, LL b, LL c) { 5 LL ans; 6 a %= c; 7 for (ans = 1; b; b >>= 1) { 8 if (b & 1) { 9 ans *= a; 10 ans %= c; 11 } 12 a *= a; 13 a %= c; 14 } 15 return ans; 16 } 17 int GCD(int x, int y) { 18 return y ? GCD(y, x % y) : x; 19 } 20 int ExtGcd(int a, int b, int &x, int &y) { 21 int t, d; 22 if (b == 0) { 23 x = 1; 24 y = 0; 25 return a; 26 } 27 d = ExtGcd(b, a % b, x, y); 28 t = x; 29 x = y; 30 y = t - a / b * y; 31 return d; 32 } 33 int InvMod(int a, int n) { 34 int x, y; 35 ExtGcd(a, n, x, y); 36 return (x % n + n) % n; 37 } 38 int main() { 39 int c, ca = 1; 40 int n, i, k; 41 LL ans; 42 scanf("%d", &c); 43 while (c--) { 44 scanf("%d%d", &k, &n); 45 ans = 0; 46 for (i = 1; i <= n; i++) { 47 ans += PowMod(k, GCD(n, i), MOD); 48 ans %= MOD; 49 } 50 if (n & 1) { 51 ans += PowMod(k, (n + 1) >> 1, MOD) * (LL) n % MOD; 52 ans %= MOD; 53 } else { 54 ans += PowMod(k, n >> 1, MOD) * (LL) (n >> 1) % MOD; 55 ans += PowMod(k, (n >> 1) + 1, MOD) 56 * (LL) (n >> 1)% MOD; 57 ans %= MOD; 58 } 59 printf("Case #%d: %I64d\n", ca++, 60 ans * InvMod(n << 1, MOD) % MOD); 61 } 62 return 0; 63 }