5

I was solving a time-complexity question on Interview Bit as given in the below image. enter image description here

The answer given is Θ(theta)(logn) and I am not able to grasp how the logn term arrive here in the time complexity of this program.

Can someone please explain how the answer is theta of logn?

Community
  • 1
  • 1
KhiladiBhaiyya
  • 633
  • 1
  • 14
  • 43

2 Answers2

2

Theorem given any x, gcd(n, m) where n < fib(x) is recursive called equal or less than x times.

Note: fib(x) is fibonacci(x), where fib(x) = fib(x-1) + fib(x-2)

Prove

Basis

every n <= fib(1), gcd(n, m) is gcd(1,m) only recursive once

Inductive step

assume the theorem is hold for every number less than x, which means:

calls(gcd(n, m)) <= x for every n <= fib(x)

consider n where n <= fib(x+1)

if m > fib(x)

   calls(gcd(n, m))
=  calls(gcd(m, (n-m))) + 1
=  calls(gcd(n-m, m%(n-m))) + 2  because n - m <= fib(x-1)
<= x - 1 + 2
=  x + 1

if m <= fib(x)

   calls(gcd(n, m))
=  calls(gcd(m, (n%m))) + 1  because m <= fib(x)
<= x + 1

So the theorem also holds for x + 1, as mathematical induction, the theorem holds for every x.

Conclusion

gcd(n,m) is Θ(reverse fib) which is Θ(logn)

Zang MingJie
  • 5,164
  • 1
  • 14
  • 27
0

This algorithm generates a decreasing sequence of integer (m, n) pairs. We can try to prove that such sequence decays fast enough.

Let's say we start with m_1 and n_1, with m_1 < n_1.

At each step we take n_1 % m_1, which is < m_1, and repeat recursively on the pair m_2 = n_1 % m_1 and n_2 = m_1.

Now, let's say n_1 % m_1 = m_1 - p for some p where 0 < p < m_1. We have max(m_2, n_2) = m_1 - p.

Let's take another step (m_2, n_2) -> (m_3, n_3), we can easily see that max(m_3, n_3) < p, but clearly it is also true that max(m_3, n_3) < m_1 - p as the sequence is strictly decreasing.

So we can write max(m_3, n_3) < min(m_1 - p, p), where min(m_1 - p, p) = m_1 / 2. This result expresses the fact that the sequence decreases geometrically, therefore the algorithm has to terminate in at most log_2(m_1) steps.

Emerald Weapon
  • 2,392
  • 18
  • 29