diff --git a/Math/#50-Pow(x,n)-Medium/Explanation-Pow(x,n).md b/Math/#50-Pow(x,n)-Medium/Explanation-Pow(x,n).md new file mode 100644 index 0000000..b2340ba --- /dev/null +++ b/Math/#50-Pow(x,n)-Medium/Explanation-Pow(x,n).md @@ -0,0 +1,5 @@ +Can use pow(x,n) surprisingly lol. + +Actual solution would be to compute powers of x by right shifting to cut down the number of multiplications since high powers would lead to TLE. + +By using this we improve the time complexity from O(n) to O(log(n)), which is very significant at higher values of n, close to 2^19 and above. diff --git a/Math/#50-Pow(x,n)-Medium/Solution-Pow(x,n).cpp b/Math/#50-Pow(x,n)-Medium/Solution-Pow(x,n).cpp new file mode 100644 index 0000000..5c49dba --- /dev/null +++ b/Math/#50-Pow(x,n)-Medium/Solution-Pow(x,n).cpp @@ -0,0 +1,17 @@ +class Solution { + public: + double myPow(double x, int n) { + double res = 1; + if(n < 0) x = 1/x; + long nums = labs(n); + while(nums){ + if(nums & 1){ + res *= x; + } + + x *= x; + nums >>= 1; + } + return res; + } + }; \ No newline at end of file