001package algs14;
002import stdlib.*;
003public class XPrintingLoops {
004        // To Print: 
005        //
006        // Test variant with one, two or three nested loops
007        //
008        // Outermost:
009        // for (long i = 1; i <= N; i = i+1)
010        // for (long i = 1; i <= N; i = i*2)
011        //
012        // Next:
013        // for (long j = 1; j <= N; j = j+1)
014        // for (long j = 1; j <= i; j = j+1)
015        // for (long j = 1; j <= N; j = j*2)
016        // for (long j = 1; j <= i; j = j*2)
017        //
018        // Next:
019        // for (long k = 1; k <= N; k = k+1)
020        // for (long k = 1; k <= j; k = k+1)
021        // for (long k = 1; k <= N; k = k*2)
022        // for (long k = 1; k <= j; k = k*2)
023
024        public static long timesTwoSum (int N, boolean print) {
025                long count = 0;         
026                for (long i = 1; i <= N; i = i*2) {
027                        for (long j = 1; j <= i; j = j+1) {
028                                if (print) StdOut.printf ("%02d ", i);
029                                count += 1;
030                        }
031                        if (print) StdOut.println ();
032                }
033                return count;
034        }
035        public static long plusOneSum (int N, boolean print) {
036                long count = 0;         
037                for (long i = 1; i <= N; i = i+1) {
038                        for (long j = 1; j <= i; j = j+1) {
039                                if (print) StdOut.printf ("%02d ", i);
040                                count += 1;
041                        }
042                        if (print) StdOut.println ();
043                }
044                return count;
045        }
046        public static void main (String[] args) {
047                plusOneSum(16, true);
048                timesTwoSum(16, true);
049                for (int N=1; N<=524288; N*=2) {
050                        long p1 = plusOneSum(N, false);
051                        long t2 = timesTwoSum(N, false);
052                        StdOut.format("N=%6d t2=%,10d p1=%,15d\n", N, t2, p1);
053                }
054        }
055}