CSCI 202 in-class lab 4

This lab is a look at recursion and a few other exciting things.

The main method

    public static void main(String[] args) {
        System.out.println("Enter your number") ;
        java.util.Scanner stdin = new java.util.Scanner(System.in) ;
        String word = stdin.next() ;
        int n ;
        try {
            n = Integer.parseInt(word) ;
        } catch (NumberFormatException nfe) {
            System.out.println("Bad input: "+ word) ;
            return ;
        }
        if (n < 0) {
            System.out.println("Too negative: " + n) ;
            return ;
        }
        if ((long)n * n > Integer.MAX_VALUE) {
            System.out.println("Too large: " + n) ;
            return ;
        }
        int x = floorSqrt(n) ;
        System.out.println("" + n + " = "
                + x + "*" + x
                + "+" + (n-x*x)) ;
        // Need -enableassertions at run time
        // Project properties -> Run -> VMoptions=-ea
        assert (x+1)*(x+1) > n && n >= x*x ;
    }

First, look at all that input validation in the main routine.

Also, notice the assert. It tells you that we are looking to set x to the smallest integer whose square is greater than or equal to n

A little recursion

Before going to the lab we are going to discuss the writing of a recursive routine that use divide-and-conquer to compute the floored square root.

Here is a javadoc style summary for this routine.

    private static int binarySqrt(int n, int hi, int lo)

This routine should only be called under the following three conditions.

  1. n, hi and lo are all positive
  2. hi2 does not exceed the range of Java ints
  3. hi2 > n and nlo2

A recursion wrapper

Use the following routine as an intermediary between main and binarySqrt.

    public static int floorSqrt(int n) {
        if (n <= 1) {
            return n ;
        } else {
            return binarySqrt(n, n, 0) ;
        }
    }

Homework 3

Homework 3 will be published and due next Thursday evening. The homework assignment will start wherever we end in lab.