askvity

How do you find the sum of digits in a number?

Published in Digit Sum Calculation 2 mins read

The sum of digits in a number is found by adding each digit of the number together. If the result is a multi-digit number, you can repeat the process until you arrive at a single-digit number, which is sometimes called the digit sum.

Understanding Digit Sum

The digit sum of a number is calculated by iteratively summing the digits until a single digit is obtained. Let's look at some examples. As the reference mentions, the digit sum of a number, say 152, is just the sum of the digits, 1+5+2=8.

Examples

Here's a breakdown with more examples:

Number Sum of Digits Digit Sum
152 1 + 5 + 2 = 8 8
786 7 + 8 + 6 = 21 2 + 1 = 3
12345 1 + 2 + 3 + 4 + 5 = 15 1 + 5 = 6

Steps to Calculate the Sum of Digits

  1. Identify the Digits: Break down the number into its individual digits.
  2. Add the Digits: Sum all the individual digits together.
  3. Repeat if Necessary: If the sum is more than one digit, repeat steps 1 and 2 using the sum as the new number, until a single-digit number is obtained.

Python Example

def digit_sum(n):
    """Calculates the digit sum of a number."""
    n = abs(n) # Handle negative numbers

    while n > 9:
        sum_digits = 0
        for digit in str(n):
            sum_digits += int(digit)
        n = sum_digits
    return n

#Example Usage
print(digit_sum(152))
print(digit_sum(786))
print(digit_sum(12345))

Related Articles