Question: p130 segment 4.2 Let's translate these algorithms into Java code. If we use long integers, we could write the following statements (see attached program). Run
p130 segment 4.2 Let's translate these algorithms into Java code. If we use long integers, we could write the following statements (see attached program).
- Run the program for n = 10000. The sum should be 50005000. How quick did each algorithm run?
- Run the program for n = 100000 (one hundred thousand). The sum should be 5000050000.
Keep adding zeros to n until the computer takes about ten seconds. Or go steps of hundred thousand,
Attachment
// @author Frank M. Carrano, Timothy M. Henry // @version 5.0 // Computing the sum of the consecutive integers from 1 to n: long n = 10000; // ten thousand // Algorithm A long sum = 0; for (long i = 1; i <= n; i++) sum = sum + i; System.out.println(sum); // Algorithm B sum = 0; for (long i = 1; i <= n; i++) { for (long j = 1; j <= i; j++) sum = sum + 1; } // end for System.out.println(sum); // Algorithm C sum = n * (n + 1) / 2; System.out.println(sum); - n = 100000,
- n = 200000,
- n = 300000, ...
How big would n have been twenty years ago? How big will n be in twenty years?
If an algorithm were the only algorithm you tried and it was too slow, what should you do? Use a faster computer? Work harder for a different algorithm?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
