Last active
August 23, 2022 13:59
-
-
Save Per48edjes/b99c95bbec6776655c2fea12b143772a to your computer and use it in GitHub Desktop.
Recursively calculate the digital root of a non-negative integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def digital_root(n: int, original=None) -> int: | |
""" | |
Return the digital root of a non-negative integer `n`. Note that this is | |
basically the same as `n % 9` except in the special case when `n` is a | |
multiple of 9. | |
@param n: A non-negative integer | |
@type n: int | |
@return: The digital root of `n` | |
@rtype : int | |
>>> digital_root(274) | |
4 | |
>>> digital_root(99999943) | |
7 | |
>>> digital_root(999999) | |
9 | |
>>> digital_root(0) | |
0 | |
>>> digital_root(108) | |
9 | |
""" | |
assert n >= 0, "`n` must be a non-negative integer" | |
original = n | |
r = 0 | |
while n: | |
r += n % 10 | |
n //= 10 | |
if r < 10: | |
return 9 if r == 0 and original > 0 else r | |
else: | |
return digital_root(r, original) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment