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!
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!
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))
.
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).