result = 0
i = 0
while i < 2**n:
result = result + i
i += 1
# end while
I'm assuming O(2^n). Python code.
result = 0
i = 0
while i < 2**n:
result = result + i
i += 1
# end while
I'm assuming O(2^n). Python code.
I think your code's time complexity is O(2^n log n)
because you are computing 2^n
, for 2^n
times.
a^b
can compute in O(log b)
for exponentiation by squaring and I think the exponential algorithm in python is O(log n)
algorithm.
So, the time complexity is O(2^n log n)
.
The time complexity is O(2n × n).
The reason is that numbers of size 2O(n) take O(n) bits to represent as int
objects. If the result of an arithmetic operation takes O(n) bits then it can't be done in less than O(n) time, because Python's int
objects are immutable.
So:
result = result + i
takes O(n) time because result
uses O(n) bits.i += 1
takes O(n) time, because i
uses O(n) bits.2**n
, for the same reason: the result of this operation uses O(n) bits. The exponentiation algorithm only does O(log n) multiplications, but the time is dominated by the last multiplication, which is like 2n/2 * 2n/2.i < 2**n
takes O(n) time because both numbers use O(n) bits.So, the loop iterates O(2n) times, and it does O(n) work on each iteration, hence the result.