I am given a number N. Keep summing the digits until a single digit result. e.g 35252 ==> 17 ==> 8 I have written the following code :
int digitSum(int n)
{
int sum = 0;
int digit;
while(n)
{
digit = n%10;
n = n/10;
sum += digit;
}
if(sum > 9)
return digitSum(sum);
else
return sum;
}
Coming to the time complexity : I am given the range for N as 0 <= N <= 10^9.
In worst case, with all 9s, the recursion will go max twice and I will get O(loglogn)
In best case, with single digit N, complexity will be O(1)
What will be the average complexity? I mean, what will be the complexity if N can be any number with no range defined.
Well known solution is n % 9 + (n % 9 == 0 ? 9 : 0).
First, your analysis is wrong, the time complexity is not O(loglogn) for worst case, it's
O(logn)
, with the following recursive formula:Now, we can show that the above is in
O(logn)
, using induction with the induction hypothesis of:T(n) <= 2logn
Showing it is
Omega(log(n))
is pretty trivial, with the observation thatT(n) >= 0
for alln
.Regarding the question at hand, what is the average time complexity, let's denote the average case complexity with
G(n)
, and let's assumen
is uniformly distributed (if it's not - that will change the analysis, and the outcome might be different).So, we can conclude
G(N)
is also inO(logN)
, so the average case analysis is still logarithmic inN
.