ProFek
ProFek

Reputation: 21

Finding the last digits sum with recursion

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?

Upvotes: 0

Views: 585

Answers (5)

user15801675
user15801675

Reputation:

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)))

Upvotes: 1

gsb22
gsb22

Reputation: 2180

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

Upvotes: 2

Lutz Lehmann
Lutz Lehmann

Reputation: 26040

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.

Upvotes: 5

Ali Aref
Ali Aref

Reputation: 2412

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

Upvotes: 0

Corralien
Corralien

Reputation: 120559

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

Upvotes: 0

Related Questions