Monday, July 24th
Can the power function be implemented without using exponents?
That is the subject of today's problem
The most obvious way was described as brute-force, namely iterating over a value, multiplying a variable any number of times;
e.g. for a positive exponent:
double ans=1.0;
if(n>0) {
for(int i=0; i<n; i++) {
ans*=x;
}
}
However, this times out for large inputs
To perform quicker, we will need to reduce the number of multiplications. For brute force there are n multiplies.
To do better we observe the fact that:
x^n = (x^2) ^(n/2)
which means inserting a multiplication to square x requires 1 multiplication, but we're saving n/2 multiplications on the outer exponent. When x is odd, the equation is:
x^n = x * (x^2)^((n-1)/2)
We can use this information to solve the problem recursively. We start with an answer of 1. Then, while n is greater than 0, we multiply x by x (squaring) then divide n by 2.
double ans=1.0;
while(n) {if(n%2==1) {ans*=x;n-=1;}x*=x;n/=2;}return ans;
If n is odd, we multiply the answer by x and reduce n by 1. This occurs during the final iteration because n will equal 1
Also, if n is negative, we multiply n by -1 and invert x
if(n<0) {n*=(-1);x=1.0/x;}
And don't forget the base case
if(n==0) return 1;
Also, since n-1 may be executed for an n at the negative boundary of integer values, we change the type of n to long
double myPow(double x, long n) {
While solving, I tried a variation of binary exponentiation, and got through the time exceeded test case, but then failed a test case where x=1.000000001 because of an inaccurate decimal place
Tricky problem, thanks to the Editorial for filling in on the time exceeded issue
Comments
Post a Comment