while(n > 0)
{
sum += n % 10;
n /= 10;
}
so, how much steps will this while loop take so that n
comes to 0
? What you do in each step, you divide n
with 10
. So, you need to do it k
times in order to come to 0
. Note, k is the number of digits in n
.
Lets go step by step:
First step is when n > 0
, you divide n
by 10
. If n
is still positive, you will divide it by 10
. What you get there is n/10/10
or n / (10^2)
. After third time, its n / (10^3)
. And after k times, its n/(10^k) = 0
. And loop will end. But this is not 0
in mathematical sense, its 0
because we deal with integers. What you really have is |n|/(10^k) < 1
, where k∈N
.
So, we have this now:
n/(10^k) < 1
n < 10^k
logn < k
Btw. its also n/(10^(k-1)) > 1
, so its:
k-1 < logn < k
. (btw. don't forget, this is base 10
).
So, you need to do logn + 1
steps in order to finish the loop, and thats why its O(log(n))
.