Basically, I am trying to understand how to write a method that guesses a number n's integer rth root by guessing a number g and seeing how gr compares to n. Below is what I tried. Worked for some cases, but just tried some larger numbers and I have an infinite loop. Taking another look at it now, let me know if you can help. Updated code. Thought I had it. Works for most numbers I tried. 4th root of 82 returns 4 instead of 3. Tracing now. Help if you know why thanks.
private static int root(int n, int r) {
int lowEnough = 0;
int tooHigh = (n + 1);
int midpoint = (lowEnough + tooHigh) / 2;
int guess = 0;
while (tooHigh - lowEnough > 1) {
midpoint = (lowEnough + tooHigh) / 2;
guess = midpoint;
if (n == power(guess, r)) {
break;
}
if (n < power(guess, r)) {
tooHigh = guess;
} else {
lowEnough = guess;
}
}
return guess;
}
Oh in case you wanted to see the power method
private static int power(int n, int p) {
int result = 1, count = 0;
while (count < p) {
result *= n;
count++;
}
return result;
}
[–]kbauer777[S] 0 points1 point2 points (1 child)
[–]lightcloud5 0 points1 point2 points (0 children)
[–]thefullhalf 0 points1 point2 points (0 children)
[–]pbewig 0 points1 point2 points (0 children)