CSCI 202 homework 3

Rules of submission

This assignment must be submitted to the Moodle submission page for Homework 3 by 11:00 PM on Friday, 8 February.

Your submission must conform to the following rules.

Preparation

This assignment is a modification of Lab 4. If you are having trouble with Lab 4, you should read the textbook’s discussion on binary search (pp. 168-172). There are many similarties between binary search and the floored square root problem of Lab 4.

The task

The assignment is to complete, and then modify, your Lab 4 program so that the floorSqrt routine works with Java’s BigInteger type rather than int’s.

To make this change, you will need to modify both floorSqrt and binarySqrt to process BinInteger’s rather than int’s. The main method must also be changed. To help you out a revised main and floorSqrt are provided below.

    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() ;
        BigInteger n ;
        try {
            n = new BigInteger(word) ;
        } catch (NumberFormatException nfe) {
            System.out.println("Bad input: "+ word) ;
            return ;
        }
        if (n.compareTo(BigInteger.ZERO) < 0) {
            System.out.println("Too negative: " + n) ;
            return ;
        }
        BigInteger x = floorSqrt(n) ;
        System.out.println("" + n + " = "
                + x + "*" + x
                + "+" + (n.subtract(x.multiply(x)))) ;
    }

    public static BigInteger floorSqrt(BigInteger n) {
        if (n.compareTo(BigInteger.ONE) <= 0) {
            return n ;
        } else {
            return binarySqrt(n, n, BigInteger.ZERO) ;
        }
    }

So how hard is this?

If Java, like C++, supported operating overloading this would be easy. All you’d need to do was change the declaration. But it doesn’t, so this homework is a drill on how well you can follow the Java documentation for a useful class using BigInteger as an example.

This means that simple int operations, such as n-x*x must be written as n.subtract(x.multiply(x)) . Work carefully and let NetBeans’ “auto popup code completion” feature help you out.

By the way, the fastest way to divide a positive number by two is to shift it right one place.