普通的求冪時間複雜度爲O(n);
但是可以有更好的算法,實際上循環log(2,n),
n^k = n^(k1*2^0 + k2*2^1 + k3*2^3 ....) k1,k2...k(log2,n)取0,1,爲k的二進制中每一個bit位
展開便可得。n^(k1*2^0) * n^(k2*2^1) * n^(k3*2^2).......
至此,一個較優的算法出現了
- #include <stdio.h>
- int power(int n, int k) {
- int ans = 1;
- while( k ) {
- if(k & 1) {
- ans *= n;
- }
- k >>= 1;
- n *= n;
- }
- return ans;
- }
- int main ( ) {
- int n, k;
- scanf("%d %d",&n, &k);
- printf("%d\n",power(n,k));
- exit(0);
- }