I am confused as to the time complexity of this code.
int a = 1;
while ( a < n ) {
a = a * 2;
}
I am new to time complexities
It's log(n). If n
is 4, the loop executes 2 times. If n
is 8, the loop executes 3 times. If n
is 16, the loop executes 4 times.
That's a logarithmic relationship, not a linear one.
If you check for the values a
can get you will see:
1, 2, 4, 8, 16, 32, ...,
and the iterations will continue until a
is smaller than n
, which means that the number of iterations is bounded by ⌈log2(n)⌉
.
You can thus conclude that the time complexity is logarithmic in n
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.