We say p is the perfect pth power of a number x if x can be expressed as another number b^p.
i.e if x=b^p , then p is the perfect pth power of x.
I have few use cases where x can be either a positive integer, negative integer or even a fraction. The first two cases can be handled easily in java, but how to find out the perfect pth power of a number x using java, when x is a fraction. Is it not true that if x is a fraction, we can simply use Math.sqrt(x) and get a number b such that b^2 =x? Then 2 will be the perfect pth power of x. Is this case even valid?
I am not necessarily looking for code, but the logic to determine the perfect pth power of x in java if x is a fraction. Also please do state your reason if anyone thinks this case is invalid.
Below is the code I wrote to handle cases where x is either a positive integer or a number between 0 and 1. But can we handle cases where x is, say for eg. 45.487,875515.54884, etc?
public class PerfectPower {
public PerfectPower() {
}
public Integer getPerfectPower(double x){
// x=b^p
int p = 0;
double b;
if(x==0){
throw new IllegalArgumentException("Cannot accept number 0.");
}
if (x > 1) {
for (b = 2; b <= x; b++) {
double value = 0;
p = 1;
while (value <= x) {
value = Math.pow(b, p);
if (value == x) {
return p;
} else if (value > x) {
break;
} else {
p++;
}
}
}
} else if(x>0 && x<1){
for (b = 2; (1/b) >= x; b++) {
double value = 1;
p = -1;
while (value >= x) {
value = Math.pow(b, p);
if (value == x) {
return p;
} else if (value < x) {
break;
} else {
p--;
}
}
}
}
return null;
}
We can do this in a simple way using logarithms. It goes as below:
So we can iterate b = 2 through x and check whether p is a perfect integer and return the value. For decimal cases we can tweak the log formula some more.
In each iteration we can check whether b^p = x and if it is return p. I solved this problem assuming p should be an integer. However for cases where p can be decimal and x between 0 to 1 this solution should be tweaked some more. Below is my code which I have implemented in scala.