This function is O(log(n)). Why? Isn't it looping up to n?
function fxn($n) {
for ($i = 1; $i <= $n; $i *= 2)
echo $i;
}
I'm pretty new to O(n) analysis by the way. This function sure looks O(n) though since it loops up to n.
It's not looping through all of the elements, in each step it jumps over twice of the elements of the previous step - because of the $i *= 2
part. That is, assuming that $i
starts in a value greater than zero, otherwise it's an infinite loop: $i
will always be 0
as it is written.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With