快速冪

普通的求冪時間複雜度爲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).......

至此,一個較優的算法出現了

  1. #include <stdio.h> 
  2.  
  3. int power(int n, int k) { 
  4.     int         ans = 1; 
  5.     while( k ) { 
  6.         if(k & 1) { 
  7.             ans *= n; 
  8.         } 
  9.         k >>= 1; 
  10.         n *= n; 
  11.     } 
  12.     return ans; 
  13. int main ( ) { 
  14.     int n, k; 
  15.     scanf("%d %d",&n, &k); 
  16.     printf("%d\n",power(n,k)); 
  17.     exit(0); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章