Using java Write a recursive method static int intSquareRoot(int n) {} // return
ID: 3842044 • Letter: U
Question
Using java Write a recursive method static int intSquareRoot(int n) {} // return the biggest number whose square is <= n. Assume n >= 0. Use recursion. No loops allowed. You will need to recurse on n/4 rather than n-1. That's because the method is called with some big values . If you recurse on n-1 those values will generate a StackOverflowError. Of course Math.sqrt() or other Math class methods are not to be used in your implementation. You're just coding this using recursion and elementary operations . Implementation Hint: intSquareRoot(n) is close to intSquareRoot(n/4) * 2. (Either equal to it or one more than it. You can tell which one, by squaring something.)
Explanation / Answer
int intSquareRoot(int n) {
if (n<3)
return 1;
int sqrt = intSquareRoot(n/4) * 2;
if (sqrt*sqrt < n){ //two if statement to fine tune sqrt value
sqrt++;
}
if (sqrt*sqrt > n){
sqrt--;
}
return sqrt;
}
I hope this makes sense. If you need more assistance on this, please feel free to comment below. I shall be glad to help you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.