Feb:25(Wed)

CS 163-01 Lab #10

Consider the following six program fragments:
  1.     sum = 0;
        for ( i = 0; i < n; i++ )
            for ( j = 0; j < 100; j++ )
                sum++;
    
  2.     sum = 0;
        for ( i = 0; i < n; i++ )
            for ( j = 0; j < n; j++ )
                sum++;
    
  3.     sum = 0;
        for ( i = 0; i < n; i++ )
            for ( j = 0; j < n * n; j++ )
                sum++;
    
  4.     sum = 0;
        for ( i = 0; i < n; i++ )
            for ( j = 0; j < i; j++ )
                sum++;
    
  5.     sum = 0;
        for ( i = 0; i < n; i++ )
            for ( j = 0; j < i * i; j++ )
                for ( k = 0; k < j; k++ )
                    sum++;
    
  6.     sum = 0;
        for ( i = 1; i < n; i++ )
            for ( j = 1; j < i * i; j++ )
                if ( j % i == 0 )
                    for ( k = 0; k < j; k++ )
                        sum++;
    
Do the following steps:
  1. Flesh out each of these six program fragments to make six complete Java programs.
    In each program, take a value for n as a command-line argument (rem. in Eclipse use Run...), and output the final value of sum.
  2. Use time to time executions of each of your six programs here trying a range of values for n as follows:
    1. What you need to type to time each execution is as follows:
          time java program_name value_for_n
      
      And among the three times reported by time, the one that is best for our purposes here is the one labeled "user".
    2. For the range of values for n, try 1000 times powers of two: 1000, 2000, 4000, ... — or actually 1000000 (one million) times powers of two for (a). Continue trying values until you get a time over twenty seconds.
Turn in your code, notes about the values you tried, and the corresponding times and final values of sum.

[Acknowledgement: this exercise is derived from Mark Allen Weiss.]