Question

Your job is to implement the root static method for NaturalNumber using the interval halving root...

Your job is to implement the root static method for NaturalNumber using the interval halving root algorithm.

Use the following skeleton (Java language) and complete the root method to achieve the proper output:

import components.naturalnumber.NaturalNumber;
import components.naturalnumber.NaturalNumber2;
import components.simplewriter.SimpleWriter;
import components.simplewriter.SimpleWriter1L;

/**
 * Program with implementation of {@code NaturalNumber} secondary operation
 * {@code root} implemented as static method.
 *
 * @author Put your name here
 *
 */
public final class NaturalNumberRoot {

    /**
     * Private constructor so this utility class cannot be instantiated.
     */
    private NaturalNumberRoot() {
    }

    /**
     * Updates {@code n} to the {@code r}-th root of its incoming value.
     *
     * @param n
     *            the number whose root to compute
     * @param r
     *            root
     * @updates n
     * @requires r >= 2
     * @ensures n ^ (r) <= #n < (n + 1) ^ (r)
     */
    public static void root(NaturalNumber n, int r) {
        assert n != null : "Violation of: n is  not null";
        assert r >= 2 : "Violation of: r >= 2";

        // TODO - fill in body

    }

    /**
     * Main method.
     *
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) {
        SimpleWriter out = new SimpleWriter1L();

        final String[] numbers = { "0", "1", "13", "1024", "189943527", "0",
                "1", "13", "4096", "189943527", "0", "1", "13", "1024",
                "189943527", "82", "82", "82", "82", "82", "9", "27", "81",
                "243", "143489073", "2147483647", "2147483648",
                "9223372036854775807", "9223372036854775808",
                "618970019642690137449562111",
                "162259276829213363391578010288127",
                "170141183460469231731687303715884105727" };
        final int[] roots = { 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 15, 15, 15, 15, 15,
                2, 3, 4, 5, 15, 2, 3, 4, 5, 15, 2, 2, 3, 3, 4, 5, 6 };
        final String[] results = { "0", "1", "3", "32", "13782", "0", "1", "2",
                "16", "574", "0", "1", "1", "1", "3", "9", "4", "3", "2", "1",
                "3", "3", "3", "3", "3", "46340", "46340", "2097151", "2097152",
                "4987896", "2767208", "2353973" };

        for (int i = 0; i < numbers.length; i++) {
            NaturalNumber n = new NaturalNumber2(numbers[i]);
            NaturalNumber r = new NaturalNumber2(results[i]);
            root(n, roots[i]);
            if (n.equals(r)) {
                out.println("Test " + (i + 1) + " passed: root(" + numbers[i]
                        + ", " + roots[i] + ") = " + results[i]);
            } else {
                out.println("*** Test " + (i + 1) + " failed: root("
                        + numbers[i] + ", " + roots[i] + ") expected <"
                        + results[i] + "> but was <" + n + ">");
            }
        }

        out.close();
    }

}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Source code:-

import components.naturalnumber.NaturalNumber;
import components.naturalnumber.NaturalNumber2;
import components.simplewriter.SimpleWriter;
import components.simplewriter.SimpleWriter1L;

public final class NaturalNumberRoot {

/**
* Private constructor so this utility class cannot be instantiated.
*/
private NaturalNumberRoot() {
}

/**
* Updates {@code n} to the {@code r}-th root of its incoming value.
*
* @param n
* the number whose root to compute
* @param r
* root
* @updates n
* @requires r >= 2
* @ensures n ^ (r) <= #n < (n + 1) ^ (r)
*/
public static void root(NaturalNumber n, int r) {
assert n != null : "Violation of: n is not null";
assert r >= 2 : "Violation of: r >= 2";
final NaturalNumber ONE = new NaturalNumber2(1);
final NaturalNumber TWO = new NaturalNumber2(2);
NaturalNumber number = new NaturalNumber2();
number.copyFrom(n);
int pow = r;
NaturalNumber lowEnough = new NaturalNumber2(0);
NaturalNumber tooHigh = new NaturalNumber2();
tooHigh.copyFrom(n);
tooHigh.increment();
NaturalNumber possibleSquare = new NaturalNumber2();
NaturalNumber difference = new NaturalNumber2();
difference.copyFrom(tooHigh);
difference.subtract(lowEnough);
while (difference.compareTo(ONE) > 0) {
possibleSquare.copyFrom(tooHigh);
possibleSquare.add(lowEnough);
possibleSquare.divide(TWO);
NaturalNumber guess = new NaturalNumber2();
guess.copyFrom(possibleSquare);
guess.power(pow);
if (guess.compareTo(number) <= 0) {
lowEnough.copyFrom(possibleSquare);
} else {
tooHigh.copyFrom(possibleSquare);
}
difference.copyFrom(tooHigh);
difference.subtract(lowEnough);
}
n.copyFrom(lowEnough);
}

/**
* Main method.
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
SimpleWriter out = new SimpleWriter1L();

final int[] numbers = { 0, 1, 13, 1024, 189943527, 0, 1, 13, 4096,
189943527, 0, 1, 13, 1024, 189943527, 82, 82, 82, 82, 82, 9,
27, 81, 243, 143489073 };
final int[] roots = { 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 15, 15, 15, 15, 15,
2, 3, 4, 5, 15, 2, 3, 4, 5, 15 };
final int[] results = { 0, 1, 3, 32, 13782, 0, 1, 2, 16, 574, 0, 1, 1,
1, 3, 9, 4, 3, 2, 1, 3, 3, 3, 3, 3 };

for (int i = 0; i < numbers.length; i++) {
NaturalNumber n = new NaturalNumber2(numbers[i]);
NaturalNumber r = new NaturalNumber2(results[i]);
root(n, roots[i]);
if (n.equals(r)) {
out.println("Test " + (i + 1) + " passed: root(" + numbers[i]
+ ", " + roots[i] + ") = " + results[i]);
} else {
out.println("*** Test " + (i + 1) + " failed: root("
+ numbers[i] + ", " + roots[i] + ") expected <"
+ results[i] + "> but was <" + n + ">");
}
}

out.close();
}

}

Add a comment
Know the answer?
Add Answer to:
Your job is to implement the root static method for NaturalNumber using the interval halving root...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Implement the static method declared as follows: /** * Divides {@code n} by 2. * *...

    Implement the static method declared as follows: /** * Divides {@code n} by 2. * * @param n *            {@code NaturalNumber} to be divided * @updates n * @ensures 2 * n <= #n < 2 * (n + 1) */ private static void divideBy2(NaturalNumber n) {...} ()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()() Implement the static method declared as follows: /** * Checks whether a {@code String} is a palindrome. * * @param s *            {@code String} to be checked * @return true if {@code...

  • You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement...

    You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement this method return new int[] {}; }    There is a utility method provided for you with the following signature. You may use this method to convert a list of integers into an array. public static int[] convertIntegers(List<Integer> integers) Provided code import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class MatrixSearch { // This method converts a list of integers to an array...

  • Here is the indexOf method that I wrote: public static int indexOf(char[] arr, char ch) {...

    Here is the indexOf method that I wrote: public static int indexOf(char[] arr, char ch) {            if(arr == null || arr.length == 0) {                return -1;            }            for (int i = 0; i < arr.length; i++) {                if(arr[i] == ch) {                    return i;                }            }        return -1;       ...

  • Copy the program DigitPlay.java and implement the TBI (To Be Implemented) method named play(Result r). Your...

    Copy the program DigitPlay.java and implement the TBI (To Be Implemented) method named play(Result r). Your program cannot contain any import statements. Your play(Result r) method cannot call any other methods. The output of your program must match the following. number: 5 # of digits: 1 smallest digit: 5 largest digit: 5 digit range: 0 digit sum: 5 digit average: 5.0 digit product: 5 number: 42 # of digits: 2 smallest digit: 2 largest digit: 4 digit range: 2 digit...

  • For the code below write a public static main() method in class Student that: - creates...

    For the code below write a public static main() method in class Student that: - creates an ArrayList<Student> object called students - adds 4 new Student objects to the students list, with some made up names and dates - sort the students list by name and display the sorted collection to System.out. use function getCompByName() - sort the students list by enrollment date and display the sorted collection to System.out. use function getCompByDate() import java.util.Comparator;    import java.util.Date;    public...

  • Part 1. Primitive Types, Sorting, Recursion for Homework.java a) Implement the static method initializeArray that receives...

    Part 1. Primitive Types, Sorting, Recursion for Homework.java a) Implement the static method initializeArray that receives as a parameter an array of integers. Use a for loop and an if statement to put 0s in the odd positions of the array and 5s in the even positions. b) Implement the static method printArray that receives as a parameter an array of integers. Use a for statements to print all the elements in the array. c) Implement the static method insertionSort...

  • Implement a greedy strategy in JAVA which takes in a list of job object ( each...

    Implement a greedy strategy in JAVA which takes in a list of job object ( each job object consist of Job id (integer) , startTime (float) and endTime(float)) and outputs a list of non-conflicting jobs according to their start time. (Implement the given method provided in the code). Example of Input: id startTime endTime 1 4 7 2 3 5 3 7 9 CODE import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.io.InputStream; public class JobScheduling { public static final Strategy...

  • Create a method based program to find if a number is prime and then print all...

    Create a method based program to find if a number is prime and then print all the prime numbers from 1 through 500 Method Name: isPrime(int num) and returns a boolean Use for loop to capture all the prime numbers (1 through 500) Create a file to add the list of prime numbers Working Files: public class IsPrimeMethod {    public static void main(String[] args)    {       String input;        // To hold keyboard input       String message;      // Message...

  • need help to write the main method as the template import java.util.*; public class oBST {...

    need help to write the main method as the template import java.util.*; public class oBST { static float optimalBST(String words[], float freq[], int n) { //2D dp matrix float dp[][] = new float[n + 1][n + 1]; int root[][] = new int[n+1][n+1]; // For a single word, cost is equal to frequency of the word for (int i = 0; i < n; i++) dp[i][i] = freq[i]; // Now consider for size 2, 3, ... . for (int L =...

  • Your code must approximate the square root of an integer between 0 and 2^31-1 Using integer...

    Your code must approximate the square root of an integer between 0 and 2^31-1 Using integer maths is sufficient (no floating point or fractions are required); your code will return the truncated (integer portion) of the square root. Your code must be in an assembly language subroutine which is called by a C function for testing. Be sure to use registers according to the ARM calling convention. Base your software on the following pseudocode: Approximate square root with bisection method...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT