Order Calculations

Nested linear loops

    int f1(int n) {
	int c = 0;
	for (int i = 0; i < n; i++)
	    for (int j = 0; j < i; j++)
		c++;
	return c;
    }

Linear surrounding log

    int f2(int n) {
	int c = 0;
	for (int i = 0; i < n; i++)
	    for (int step = i; step > 0; step /= 3)
		c++;
	return c;
    }

Log surrounding linear

    int f3(int n) {
	int c = 0;
	for (int step = n; step > 0; step /= 3)
	    for (int i = 0; i < step; i++)
		c++;
	return c;
    }
Yes, it’s linear.

Test question

    int f4(int n) {
	int c = 0;
	for (int j = 0; j < n; j++) {
	    for (int step = n; step > 0; step /= 3)
		for (int i = 0; i < step; i++)
		    c++;
	    for (int k = 0; k < 100; k++)
		c++;
	}
	return c;
    }
Sample code: q1.c q2.c q3.c q4.c