THINK FIRST·CODE LATER

← All labs

Counting operations and the doubling test

Problem

Write GrowthTable with four methods that count how many times their innermost statement runs:

  • halving(n): for (i = n; i >= 1; i /= 2);
  • linearithmic(n): a loop of n iterations around the halving loop;
  • triangular(n): for i in 0..n-1, for j in i+1..n-1;
  • cubic(n): three nested loops of n.

Read n and a number of rows; print one row per size, doubling n each time, and finally by what factor the last doubling multiplied the n²/2 and n³ counts.

For the input

10 4

the program prints

n      log    n log n      n^2/2          n^3
    10        4         40         45         1000
    20        5        100        190         8000
    40        6        240        780        64000
    80        7        560       3160       512000
Doubling n multiplied n^2/2 by 4.05 and n^3 by 8.00

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d6-3-data-1.txt

10 4
What your program must print for d6-3-data-1.txt
n      log    n log n      n^2/2          n^3
    10        4         40         45         1000
    20        5        100        190         8000
    40        6        240        780        64000
    80        7        560       3160       512000
Doubling n multiplied n^2/2 by 4.05 and n^3 by 8.00

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d6-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content d6-3-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.