Monday, November 12, 2018

Q12 : Sum of Digits / Digital Root

A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

Here's how it works:

digital_root(16)
=> 1 + 6
=> 7

digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6

digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6

digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2

4 comments:

  1. def digital_root(val):
    if len(str(val)) == 1:
    return val
    else:
    return digital_root(sum(map(int, str(val))))

    print(digital_root(16))

    ReplyDelete
  2. def digital_root(num):
    if len(str(num)) == 1:
    return num
    else:
    return digital_root(sum([int(s) for s in str(num)]))

    ReplyDelete
  3. >>> digital_root = lambda s: s if len(str(s)) == 1 else digital_root(sum([int(i) for i in str(s)]))
    >>> digital_root(12)
    3

    ReplyDelete
  4. def digital_root(number):
    if number>9:
    number = sum([int(i) for i in str(number)])
    return digital_root(number)
    else:
    return number
    print(digital_root(int(input())))

    ReplyDelete