/** CountOps.java - Let's see how we can instrument code by hand to * count the number of operations performed. Then, if we run * several times with different input size, we can observe trends * and intuitively conclude the code's run-time complexity. */ public class CountOps { public static int work(int n) { // Account for allocating space for array. int ops = 1; int [][][] a = new int [n][n][n]; /* Here is the loop without the instrumentation for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) for (int k = 0; k < n; ++k) { if (i == j || i == k || j == k) a[i][j][k] = 1; else a[i][j][k] = i + j + k; } */ ops += 2; // Account for the i = 0 and i < n for (int i = 0; i < n; ++i) { ops += 2; // Account for the j = 0 and j < n for (int j = 0; j < n; ++j) { ops += 2; // Account for the k = 0 and k < n for (int k = 0; k < n; ++k) { // Account for evaluating the conditional expression. // A slight overestimation because short-circuit evaluation // means we might not have to evaluate all of it. ops += 5; if (i == j || i == k || j == k) { // Account for doing the store operation, but I'm not // accounting for the address calculation. ++ops; a[i][j][k] = 1; } else { ops += 3; // Account for the store and two adds. a[i][j][k] = i + j + k; } ops += 2; // Account for the ++k and k < n } ops += 2; // Account for the ++j and j < n } ops += 2; // Account for the ++i and i < n } // Return the number of operations performed. return ops; } public static void main(String [] args) { // Call the work() function several times, each with a different // input size (n). We expect an n^3 time complexity, // so let's look at the coefficient of n^3 by dividing by n^3. // But what we weren't sure if it was n^2 or n^4 instead? System.out.printf(" n ops coef of n^2 coef of n^3 coef of n^4\n"); for (int n = 10; n <= 80; n += 10) { int numOps = work(n); double coef2 = (double) numOps / (double) (n*n); double coef3 = (double) numOps / (double) (n*n*n); double coef4 = (double) numOps / (double) (n*n*n*n); System.out.printf("%3d %8d %11.3f %11.3f %11.3f\n", n, numOps, coef2, coef3, coef4); } } } /* Output: n ops coef of n^2 coef of n^3 coef of n^4 10 9883 98.830 9.883 0.988 20 79363 198.408 9.920 0.496 30 268443 298.270 9.942 0.331 40 637123 398.202 9.955 0.249 50 1245403 498.161 9.963 0.199 60 2153283 598.134 9.969 0.166 70 3420763 698.115 9.973 0.142 80 5107843 798.100 9.976 0.125 Notice that the coefficients of n^2 don't converge, the coefficients of n^4 tend to zero, and the coefficients of n^3 tend to a non-zero constant. This suggests that n^3 is the way to go. */