Finding the last digits sum with recursion

534 Views Asked by At

I'm attempting to create a function that will sum all the digits
and will return the sum of the summarized number.

Example:
For Input getNumValue(1589)
The Output will be: 5
Becuase: 1 + 5 + 8 + 9 = 23
And 2 + 3 = 5
So the output will be 5
Because we can't split it into more digits.

I did managed to create a recursion function that summarize the digits:

def getNumValue(number: int):
    if number == 0:
        return 0
    return (number % 10 + getNumValue(int(number / 10)))

But I can't seem to utilize it to my cause.

Btw
I don't want to use any strings
And I'm trying to use recursion so far no luck.
I bet this is a known mathematic problem I'm just unfamiliar with.
Any advice?

5

There are 5 best solutions below

8
Lutz Lehmann On BEST ANSWER

Even shorter:

def getNumValue(number: int): return ((number-1) % 9) + 1

The digit sum is always in the same remainder class mod 9 as the original decimal number, this applies recursively, and thus reducing it to one digit just is the remainder under division by 9.

The shift by 1 just serves the purpose that the remainder class 0 is represented by 9.

1
gsb22 On

you can make a final check before returning the answer.

def getNumValue(number: int):
    if number == 0:
        return 0
    answer = (number % 10 + getNumValue(int(number // 10)))
    if answer < 10:
        return answer
    return getNumValue(answer)


print(getNumValue(15899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999))

OUTPUT :

9
1
AudioBubble On

You can check if number is greater than 9. If yes, then call the function again:

def getNumValue(number: int):
    if number == 0:
        return 0
    j=(number % 10 + getNumValue(int(number // 10)))
    if j>9:
        return getNumValue(j)
    return j
print(getNumValue(getNumValue(1589)))
0
Corralien On

Without recursion:

def getNumValue(number: int) -> int:
    while True:
        total = 0
        while number:
            total += number % 10
            number //= 10
        number = total
        if total <= 9:
            return total
>>> getNumValue(number)
5
0
Ali Aref On

pythonic recursion :)

def getNumValue(number=1589):
    ans = number % 10 + getNumValue(int(number / 10)) if number else 0
    return getNumValue(ans) if ans > 10 else ans

output

5