I am trying to measure the time complexity of a algorithm. The algorithm has a while inside a while, starting by 1. Ok. But the problem is that the i increments with a product. I'm not using the big O, only counting the instructions. I'm trying to find a pattern.
In this example, I did it right:
i = 1; -> // 1 execution
while(i<=n) { // n+1
j =1; // n
while(j<=n) { // n²
....
j = j + 1; // n² * 2
}
i = i + 1; // 2n
}
Ok. I just have to sum.
But the problem is in this case:
i = 1; // 1 execution
while(i<n) { // n execution?
System.out.println("*"); // n execution?
i = i * 2; // n execution????
}
I've tested too many ways:
When n is 2 ---> The println run 1 time.
When n is 3 ---> The println run 2 times.
When n is 4 ---> The println run 2 times.
When n is 5 ---> The println run 3 times.
When n is 6 ---> The println run 3 times.
What's the pattern?
I don't want in the Big O notation.
The complexity is O(log(n))
because we divide i
by 2 in each iteration so let's say that while loop will be executed m times them we have 2^m<=n
which implies m<=log(n)
so it's O(log(n))
.