本題會用到上次在CSES Exponentiation 題解 | R3X’s Blog講到的東西,並假設讀者都已看過。

題目

  • Time limit: 1.00 s
  • Memory limit: 512 MB

Your task is to efficiently calculate values abca^{b^c} modulo 109+710^9+7.
Note that in this task we assume that 00=10^0=1.

Input Output
The first input line contains an integer nn: the number of calculations.
After this, there are nn lines, each containing three integers a,ba, b and cc.
Print each value abca^{b^c} modulo 109+710^9+7.

Constraints

  • 1n21051 \le n \le 2 \cdot 10^5
  • 0a,b,c1090 \le a,b,c \le 10^9

Example:

Input Output
3
3 7 1
15 2 2
3 4 5
2187
50625
763327764

解法

這題跟前一題差不多,我們只要額外想如何處裡aa上面的bcb^c即可。因為M=109+7M = 10^9+7是質數,所以我們可以用費馬小定理,即aM11(modM)a^{M-1}\equiv 1\pmod{M}。於是我們只要先計算出tbc(modM1)t\equiv b^c \pmod{M-1}(這樣能有效的讓aa的指數變小),再計算ata^t即可。指數計算則用我們上次提到的快速冪。

AC Code

#include<bits/stdc++.h>
using namespace std;

const int M = (int)1e9 + 7;
#define ll long long

ll fast_pow(ll base, ll exp, int m){
  ll res = 1LL;
  while(exp > 0){
    if(exp%2==1){res = (res*base) % m;}
    base = (base*base) % m;
    exp /= 2;
  }
  return res;
}

int main(){
  ios::sync_with_stdio(0), cin.tie(0);
  ll n, a, b, c;
  cin >> n;
  while(n--){
    cin >> a >> b >> c;
    cout << fast_pow(a, fast_pow(b,c,M-1),M) << "\n";
  }
}