Given two integer a and b (b >= 0), please write a function to return the result of "a to the power of b".
My Anwser: (I am no sure if it is correct.)
The easiest way is recursively multiply integer a.
int power(int a, int b) { if (b <= 0) return 1; return a * power(a, b-1); }
Question:
Improve time complexity to log(n)
My Anwser: (I am no sure if it is correct.)
Consider a to the power of 15 is power(a, 8) * power(a, 4) * power(a, 2) * power(a, 1) * power(a, 0)
#include "stdafx.h" #includeusing namespace std; int getPower(int a, int b); int power(int a, int b); int _tmain(int argc, _TCHAR* argv[]) { int a = 2, b = 15; cout << power(a, b) << endl; cin.get(); return 0; } int getPower(int a, int logb) { if (logb <= 0) return 1; return a * getPower(a*a, logb-1); } int power(int a, int b) { if (b == 0) return 1; int logb = 0; while(b>0) { logb++; b >>= 1; } return getPower(a, logb); }
沒有留言:
張貼留言