計算 x^n
1 #include <iostream>
2 using namespace std; 3 4 template<typename T> 5 inline T power(T x, unsigned int n) { 6 T ret = (n%2) ? x : T(1); 7 8 while (n >>= 1) { 9 x = x * x; 10 if (n % 2) { 11 ret = ret * x; 12 } 13 } 14 15 return ret; 16 } 17 18 template<typename T> 19 inline T rec_power(const T &x, unsigned int n) { 20 if (!n) return T(1); 21 else if (n == 1) return x; 22 23 T ret = rec_power(x, n >> 1); 24 ret *= ret; 25 if (n % 2) ret *= x; 26 27 return ret; 28 } 29 30 int main(void) { 31 cout << power(4, 0) << endl; // Output: 1 32 cout << power(1.3, 2) << endl; // Output: 1.69 33 cout << power(6, 3) << endl; // Output: 216 34 35 cout << rec_power(4, 0) << endl; // Output: 1 36 cout << rec_power(1.3, 2) << endl; // Output: 1.69 37 cout << rec_power(6, 3) << endl; // Output: 216 38 39 return 0; 40 } 41 |
#include <iostream> using namespace std; template<typename T> inline T power(T x, unsigned int n) { T ret = (n%2) ? x : T(1); while (n >>= 1) { x = x * x; if (n % 2) { ret = ret * x; } } return ret; } template<typename T> inline T rec_power(const T &x, unsigned int n) { if (!n) return T(1); else if (n == 1) return x; T ret = rec_power(x, n >> 1); ret *= ret; if (n % 2) ret *= x; return ret; } int main(void) { cout << power(4, 0) << endl; // Output: 1 cout << power(1.3, 2) << endl; // Output: 1.69 cout << power(6, 3) << endl; // Output: 216 cout << rec_power(4, 0) << endl; // Output: 1 cout << rec_power(1.3, 2) << endl; // Output: 1.69 cout << rec_power(6, 3) << endl; // Output: 216 return 0; } |
沒有留言:
張貼留言