I have written a small piece of code to find the power of a number
Can any one tell me how to find the time complexity of this code. and what is the time complexity of this code. and is it a efficient way to find powers of a number
the code is :
public static void main(String[] args) {
System.out.println(optPower(7, 15));
}
static int optPower(int x, int y) {
// divide in buckets
if (y == 0) {
return 1;
}
if (y == 1) {
return x;
}
if (y == 2)
return x * x;
int tmpY;
boolean isYmodified = false;
if (y % 2 == 0) {
tmpY = y;
} else {
tmpY = y - 1;
isYmodified = true;
}
int biggestBucket = 2;
int n = biggestBucket;
/*
* tmpY/4 , here '4' can be used as a tweking parameter to size the
* buckets
*/
while (tmpY % n == 0 && tmpY / 4 >= n) {
biggestBucket = n;
n = n * 2;
}
int res = 1;
for (int i = 0; i < biggestBucket; i++) {
res = res * x;
}
int mul = res;
for (int j = 1; j < tmpY / biggestBucket; j++) {
mul = mul * res;
}
return isYmodified ? mul * x : mul;
}
As requested, I have added more notes for clearer explanation of the algorithm.
if I want to compute 5
raise to 16
step 1:-
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
here x=5
, y=16
in the above method
if y
is odd we multiple an extra x
in the final result and assign tmpY
as y-1
to make it even
so noOfBuckets = 4 because of below code
while (tmpY % n == 0 ) {
biggestBucket = n;
n = n * 2;
}
that is
16/(2 raise to 2)
step 2:-
divide 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 into 4 buckets
bucket1 :- 5,5,5,5
bucket2 :- 5,5,5,5
bucket3 :- 5,5,5,5
bucket4 :- 5,5,5,5
step 3:-
compute bucket 1 only and use the result of this bucket for remaining buckets
result of bucket 1 = 625 = 5*5*5*5
step 4 :-enter code here
final result is bucket1*bucket1*bucket1*bucket1
i.e 625 * 625 * 625 * 625
i.e. 5
raise to 16
then we are avoiding iterations in bucket 2,3,4 and directly using the value from bucket 1 to get to the final result.