Reputation: 2246
So I need a mathematical expression for the following loop, but I can't seem to grasp it. I am assuming I am just missing something simple.
while a <= b
a = a + a
end
Using an analysis, what would be the run time of this function?
Upvotes: 1
Views: 12785
Reputation: 23265
Since you're doubling a
every time, you need log(b/a)
doublings before the loop will exit. So the run time is Theta(log(b/a))
.
Upvotes: 1
Reputation: 14434
Would you agree that each iteration of the loop doubles a
? If so, then let a
have an initial value of 1. After one iteration, a == 2
. After two iterations a == 4
. After three, a == 8
. After four, a == 16
; and so on.
Suppose that b == 64
. The loop will run seven iterations in this case. Observe that log_2(64) == 6
.
Suppose that b == 128
. The loop will run eight iterations in this case. Observe that log_2(128) == 7
.
Suppose that b == 256
. The loop will run nine iterations in this case. Observe that log_2(256) == 8
.
Therefore, the run time depends on the logarithm of b
.
Upvotes: 1
Reputation: 881253
The run time is dependent on the logarithm of b
. In other words, the time complexity is O(log N)
.
You can see this if you start a
at 1 and b
at 256. Each time through the loop, a
is doubled so that there are only nine iterations (would be eight if the condition was < b
).
Each doubling of the b
value will result in one extra iteration.
Of course, this is complexity analysis, the runtime depends on a host of other factors such as (almost certainly not an exhaustive list):
a
: a == 0
gives infinite run time, a == b + 1
gives you constant run time.Upvotes: 3