Starting from:
$35

$29

Homework 5 Solution

Write the answers to these problems on paper. Scan the paper and upload to the submissions folder.

We will grade a random subset of these for credit.

    1. 1.3.19   (You may assume the list has at least one node).

    2. 1.4.5(show your work)

    3. 1.4.6(it might help to try some small values of N – see if you see a pattern.

    4. Review the Java program on the next page.

Carefully compare the two functions: addTwoIntsNtimes, addThreeIntsNtimes and review how they are called from main.

Answer the three questions Q1, Q2, Q3 in the comments in the main function.

Q1.

Q2.

Q3.


    5. Create a java program with this class and run it using the values in the table below. (You will need to change the value of the variable reps in the program). Record the value printed in the table.

Reps    Printed value of diff


10000

100000

1000000

10000000

100000000

1000000000



Vers 1.0

package algs11;

import stdlib.In;

import stdlib.StdOut;
import stdlib.StdRandom;

import stdlib.Stopwatch;

public class ArithTimer {

public static int addTwoIntsNtimes(int reps) {

int a,b,c, sum =0;


c = StdRandom.uniform(0,1000);


for (int i = 1; i <= reps; i++) {
// get two random ints from 0 to 9999
a=StdRandom.uniform(1000);

b=StdRandom.uniform(1000);
// add two ints
c = a+b;

sum = sum + c;
// don't let sum get too big
sum = sum % 12345;

}


return sum;


}


public static int addThreeIntsNtimes(int reps) {

int a,b,c, sum =0;


c = StdRandom.uniform(0,1000);


for (int i = 1; i <= reps; i++) {
// get two random ints from 0 to 9999
a=StdRandom.uniform(1000);

b=StdRandom.uniform(1000);
// add
three ints
c = b + a + c;


sum = sum + c;
// don't let sum get too big
sum = sum % 12345;

}


return sum;


}


public static void main(String[] args)
{

int result1, result2, reps;


double time1,time2, diff;


reps = 10000;
// number of repetitions
Stopwatch timer1 = new Stopwatch();

result1 = addTwoIntsNtimes(reps);
// Q1.
average time to ________ ?
time1 = timer1.elapsedTime()/reps;



Stopwatch timer2 = new Stopwatch();



result2 = addThreeIntsNtimes(reps);
//
Q2.
average time to________ ?
time2 = timer2.elapsedTime()/reps;



diff = (time2-time1);
//
Q3.
average time to _________?

StdOut.format(" time value:    %e \n", diff);

}
}


More products