Python Challenges: Find the sum of the digits of a given number
Python Challenges - 1: Exercise-45 with Solution
Write a Python program to find the sum of the digits of a given number.
In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,
5!= 5 x 4 x 3 x 2 x 1 = 120
and the sum of the digits in the number 5! is 1 + 2 +0 = 3
Sample Solution:
Python Code:
import math
def compute(n):
n = math.factorial(n)
ans = sum(int(c) for c in str(n))
return str(ans)
print(compute(5))
print(compute(6))
Sample Output:
3 9
Flowchart:
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to find the maximum total from top to bottom of the triangle below.
Next: Write a Python program to compute the sum of all the amicable numbers under a given number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/challenges/1/python-challenges-1-exercise-45.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics