Python programs to calculate the sum of the digits of an integer have been shown here. For example if a number is $12345$ then the sum of the digits is $1 + 2 + 3 + 4 + 5$ i.e. $15$. The following section covers the iterative approach to find the sum of digits. The algorithm, time complexity and pseudocode of the program have been shown below.
Page Contents:
1. Algorithm to calculate sum of digits of an integer
1. Take a number x as input.
2. Initialize a variable to 0 say sum = 0.
3. Perform r = x % 10 and add r to sum i.e sum = sum + r
4. Perform x = x / 10
5. If x = 0 stop the process and display sum as output else go to step 3.
2. Pseudocode to calculate sum of digits of an integer
Input : A number $n$
Output : The sum of digits of $n$
1. Procedure sumOfDigits($n$):
2.
3.
4.
5.
6.
7. End Procedure
3. Time complexity to calculate sum of digits of an integer
Time Complexity: O(log(n))
Where n is the input number.
4. Program & output to calculate sum of digits of an integer
4.1. Python Program & output to calculate sum of digits of an integer using iteration
# **************************************** # alphabetacoder.com # Python program to calculate the sum of # digits of an integer using iteration # **************************************** # take input of the number num = int(input("Enter the integer = ")) # initialize s = 0 # find sum of the digits while num != 0: # extract the unit digit r = num % 10 # do sum s = s + r # divide the number by 10 num = num // 10 # display result print("Sum of digits = ", s)
Output
Enter the integer = 12548
Sum of digits = 20
4.2. Python Program & output to calculate sum of digits of an integer using recursion
# **************************************** # alphabetacoder.com # Python program to calculate the sum of # digits of an integer using recursion # **************************************** # recursive function to calculate sum of digits def digit_sum(num): if num == 0: return 0 else: return (num % 10) + digit_sum(num // 10) def main(): # take input of the number num = int(input("Enter the integer = ")) # calculate the sum by calling function # and display the result print("Sum of digits =", digit_sum(num)) # driver code main()
Output
Enter the integer = 554488
Sum of digits = 34