+ 1

Question regarding time complexity !

def logn(n): while(n>1): n = math.floor(n/2) Here n = 8. In the above code, the time complexity if O(log n). My question is if I put n/3 in place of n/2, will the time complexity remain as O(log n) ???

10th Aug 2022, 7:00 AM
Levi
Levi - avatar
6 ответов
+ 2
Your algorithm has a time complexity of O(log2(n)). By changing n/2 to n/3, i'm pretty sure it will be O(log3(n)).
10th Aug 2022, 7:42 AM
Arthur Le Floch
+ 2
Harsha S Using nested "for" loops or such, it is quite obvious : for x in range(n) : for y in range(n) : [...] # in O(1) This one is O(n^2), because there are n*n times the O(1) operations. However, depending on the type of program you use, it will be harder (the one proposed by Levi is "harder"). I will explain it in my next post.
10th Aug 2022, 8:22 AM
Arthur Le Floch
+ 2
Levi & Harsha S The complexity C(n) here can be dominated by a sequence (mathematically speaking) when n isn't a power of 3: Let's say p = log3(n) U(n) = 1 + U(ceil(n/3)) (1 for value assignation for n, the other for the next loop iteration) So U(3**p) = 1 + U(3**(p-1)) So U(3**p) = p considering U(3**0)=0 We have 3**p <= n <= 3**(p+1) So C(n) <= U(n) <= U(3**(p+1)) = p+1 <= log3(n) + 1 (with an equalty when n is a power of 3) So we have a complexity of O(log3(n)+1), which is O(log3(n)). (i'm writing this on my phone, sorry if there's any typo) That is the idea for that kind of script.
10th Aug 2022, 8:43 AM
Arthur Le Floch
+ 1
Arthur Le Floch how do i calculate time complexity
10th Aug 2022, 8:03 AM
Harsha S
Harsha S - avatar
+ 1
Arthur Le Floch thank you
10th Aug 2022, 8:23 AM
Harsha S
Harsha S - avatar
0
What do you mean under „the time complexity if O(log n)“?
10th Aug 2022, 7:11 AM
JaScript
JaScript - avatar