Блог пользователя arman_ferdous

Автор arman_ferdous, история, 9 лет назад, По-английски

Recently I wrote this code to find the sum of all the digits of the number until the number turns into a one digit number. For example: number 567, we add all the digits and we get 5+6+7 = 18, now we add all the digits of 18 and we get 1+8 = 9. We can't add anymore digits because there is only one left and thus the result is 9.

Now I am having trouble figuring out the time complexity of this recursive code. Can anyone help?

int digSum(int n)
{
    if(n < 10) return n;
    return digSum(digSum(n/10) + n%10);
}
  • Проголосовать: нравится
  • +9
  • Проголосовать: не нравится

»
9 лет назад, скрыть # |
 
Проголосовать: нравится +22 Проголосовать: не нравится

It is . But this code is really strange. It works only because ans = 1 + (n - 1)%9.