Analyze the time complexity of the following program segment. s = 0; for (i = n; i>0; i/=2) { for (j = 0; j <= i; j++) { s += j; } }
Explanation / Answer
public class myJavaApp { public static void main(String[] args) { int s = 0; int n = 4; // The following line says: "The Value of integer (i) is equal to whatever you set (n) to be." // While (i) is greater than 0, divides left operand with the right operand and assign the result to left operand //If n = 4 and i is equal to n, then n = 4, While i (whitch is now 4) is greater than 0, divide 4 into 2 an assign the value back to i // i is now 2 for (int i = n; i > 0; i/= 2) { System.out.println("The Value of "i": " + i + " "); //The following puts a for loop inside the for loop above. This loop is now nested inside. //integer j is equal to 0. Run while j (zero) is less than or equal to i. And add 1 to j. //(s) that is assigned to zero above will take the value of j by being assigned the right operand plus and equal. for ( int j = 0; j