-2

I have the following algorithm but I dont know its' complexity. Could someone help me? Input size is n.

int x = n;
while (x > 0)
{
    System.out.println("Value is" + x);
    x = x/5;
}

Thanks a lot!

idelara
  • 1,786
  • 4
  • 24
  • 48
  • I assume it should be O(log n), since the input will be smaller than n every pass of the while loop, therefore is not O(n) (because say, if n = 10, the while loop will not run 10 times) also it is not O(1) – idelara May 12 '15 at 11:13
  • 2
    Log n (to the base 5). Because you are dividing the input by 5 each time – TheLostMind May 12 '15 at 11:14
  • @TheLostMind yeah right? Do you agree with my explanation above? (comment) – idelara May 12 '15 at 11:14
  • For n= 25 the loop will run 2 times which is Log(25) to base 5. So complexity is logn to base 5. – akhil_mittal May 12 '15 at 11:14
  • 1
    @JackGal - Honest opinion. *Eran* actually gives a better explanation :). You were *almost* there :) – TheLostMind May 12 '15 at 11:16

2 Answers2

3

In each iteration x is divided by 5. How many iterations would it take for x to become lower than 1 (and therefore 0)?

The answer is log5(n) (logarithm to the base 5 of n), which is O(log(n)).

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Let T(n) be the number of operations performed for the input n.

Each iteration performs O(1) operations. So:

T(n) = O(1) + T(n/5)
     = O(1) + O(1) + T(n/25) = 2*O(1) + T(n/25)
     = 2*O(1) + O(1) + T(n/125) = 3*O(1) + T(n/125)

Each iteration add O(1) to the complexity and you will run until n/(5^a) < 1 where a is the number of iterations performed (since your input is integer).

When will the condition hold? Simply take log5 (log in base 5) on both sides of the inequality and get:

log5(n/(5^a)) < log5(1) = 0
log5(n) - log5(5^a) = 0
log5(n) = a*log5(5)       [because log(b^c) = c*log(b)]
log5(n) = a

Therefore, you will need log5(n) iterations, each one adding O(1) and so your complexity is log5(n).

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28