CSES Exponentiation II 題解
本題會用到上次在CSES Exponentiation 題解 | R3X’s Blog講到的東西,並假設讀者都已看過。
題目
- Time limit: 1.00 s
- Memory limit: 512 MB
Your task is to efficiently calculate values modulo .
Note that in this task we assume that .
| Input | Output |
|---|---|
| The first input line contains an integer : the number of calculations. After this, there are lines, each containing three integers and . |
Print each value modulo . |
Constraints
Example:
| Input | Output |
|---|---|
| 3 3 7 1 15 2 2 3 4 5 |
2187 50625 763327764 |
解法
這題跟前一題差不多,我們只要額外想如何處裡上面的即可。因為是質數,所以我們可以用費馬小定理,即。於是我們只要先計算出(這樣能有效的讓的指數變小),再計算即可。指數計算則用我們上次提到的快速冪。
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";
}
}
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 R3X's Blog!



![[Note] Writing a simple Program in C - LiveOverflow](/2026/06/03/Note-Writing-a-simple-Program-in-C-LiveOverflow/output.png)