Lab: Recursion on NaturalNumber – Instance Methods
Objective
In this lab you will practice recursion on NaturalNumbers by
implementing the subtract and power instance methods in a new
class that extends NaturalNumber2.
Setup
Follow these steps to set up a project for this lab.
- Create a new Eclipse project by copying
ProjectTemplate. Name the new projectRecursionOnNaturalNumber2. - Open the
srcfolder of this project and then open(default package). For this lab, you will need two files. As a starting point you can use any of the Java files. Rename oneNaturalNumberInstanceOpsand another oneNaturalNumberTestand delete the other files from the project. - Follow the link to
NaturalNumberInstanceOps.java, select all the code on that page and copy it to the clipboard; then open theNaturalNumberInstanceOps.javafile in Eclipse and paste the code to replace the file contents. Save the file. - Follow the link to
NaturalNumberTest.java, select all the code on that page and copy it to the clipboard; then open theNaturalNumberTest.javafile in Eclipse and paste the code to replace the file contents. Save the file.
Method
- In
NaturalNumberInstanceOps.java, complete the body of thesubtractmethod. The contract is available in theNaturalNumbercomponent documentation. For this method you can use any ofNaturalNumbermethods (except just making a single direct call tosubtractas your implementation). The code foraddis provided as an example of a recursive instance method onNaturalNumber. - Run the
NaturalNumberTestprogram and test your implementation ofsubtract. - Back in
NaturalNumberInstanceOps.java, complete the body of thepowermethod. The contract is available in theNaturalNumbercomponent documentation. For this method you can use any ofNaturalNumbermethods (except just making a single direct call topoweras your implementation). Make sure you implement the fast recursive powering algorithm discussed in class (Slides #54-57 in Recursion: Thinking About It). - Again run the
NaturalNumberTestprogram and test your implementation ofpower.
Additional Activities
- Using recursion implement the
multiplyinstance method (seeNaturalNumber). You will need to useaddas well as the kernel methods. - Implement the
powerinstance method using the fast powering algorithm but without using recursion. Good luck!