【筆記】C++ 快速冪

快速冪:快速計算 x 的 n 次方。
原理:如果想算 210,可以拆成 25 * 25 ,我們算一遍 25 就好。
時間複雜度:O(n) 降到 O(log n)。

#include <iostream>
using namespace std;

long long fastpow(int x, int n){
    if(n == 0) return 1;
    long long ans = fastpow(x, n/2);
    if(n % 2 == 0) return ans * ans;
    return ans * ans * x;
}

int main(){
    cout << fastpow(2, 10);
}




發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *