Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

programming language is JAVA: Write a recursive method static int intSquareRoot(

ID: 3841176 • Letter: P

Question

programming language is 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

class SquareRoot

{

private const double VerySmall = 0.000000001;

static void Main(string[] args)

{

double n;

double x = Value(NumOfDigits(n));

double R = RecursiveSqrt(n, x);

Console.WriteLine("The square root of {0} is (recursive): {1}", n, R);

Console.ReadKey();

}

static int NumOfDigits(double d)

{

int num = (int)Math.Round(d);

int digits = 0;

while (num > 0)

{

num/=10;

digits++;

}

return digits;

}

static double Value(int y)

{

return (y % 2) == 0 ? 7 * Math.Pow(10,(y - 2) / 2) : 2 * Math.Pow(10,(y - 1) / 2);

}

static double RecursiveSqrt(double n, double x)

{

if (Math.Abs(n - x * x) < VerySmall) return x;

return RecursiveSqrt(n, 0.5 * (x + n / x));

}

}