double fast_pow(double a, int n) {
? ? double res = 1.0;
? ? while (n > 0) {
? ? ? ? if (n & 1) res *= a; ?// 如果當前位是1,累乘
? ? ? ? a *= a; ? ? ? ? ? ? ? // 平方
? ? ? ? n >>= 1; ? ? ? ? ? ? ?// 右移一位(相當于 n /= 2)
? ? }
? ? return res;
}
功能說明
-
輸入:
-
a
:底數(支持整數或浮點數)。 -
n
:非負整數指數(如果?n < 0
,需額外處理)。
-
-
輸出:anan(例如?
fast_pow(2, 10)
?返回?1024
)。 -
時間復雜度:O(log?n)O(logn),比?
pow()
?的庫函數實現更快。