CSES Exponentiation 題解
題目
- 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 two integers and . |
Print each value modulo . |
Constraints
Example:
| Input | Output |
|---|---|
| 3 3 4 2 8 123 123 |
81 256 921450052 |
解法
快速冪
理論
要快速計算乘方,這題顯然就是快速冪。
我們以一個例子解釋快速冪的邏輯。假設我們要計算,我們其實不需要真的將做次乘法,而可以依序計算、、、、。這樣可以讓指數的大小本身亦以指數增長,進而讓的時間複雜度從降到
對於一般(非的次冪)的指數,快速冪的邏輯如下:
欲計算,先將以二進位表示(這麼做是為了用指數律將拆成若干個相乘,其中每個次方都是的冪次,而由上我們可知的冪次很好算)。舉例來說,若,則。接下來便是照我們上面說的一次把都算出來,再相乘即可。
但其實實務上我們不是這樣做的,實務上做法是:
如果指數是偶數(設),那麼;
如果指數是奇數(設),則把拆成。
如此我們每經一次操作,指數都會變成約原先的一半。
處理模數
題目額外要求了要將答案模,就是因為計算過程中出現的數字和答案可能太大。但這不困難,只要將上述快速冪中每個乘法步驟都取模即可。
C++ Code
綜合以上,我們有快速冪的程式如下:
#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;
}
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;
cin >> n;
while(n--){
cin >> a >> b;
cout << fast_pow(a,b,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)