You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Write a function that calculates the sum of the digits of the factorial of a number. n! means n x (n − 1) ... x 3 x 2 x 1. For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, and the sum of the digits in the number 10! is 3 +たす 6 +たす 2 +たす 8 +たす 8 +たす 0 +たす 0 =わ 27. Find the sum of the digits in the number 100!
3
3
4
-
f=10# Factorial number = 10
4
+
print("Factorial & Digit Sum Calculator")
5
+
f=input("Enter a number: ")
5
6
n=1# start at 1
6
7
7
-
foriinrange(1, f+1): # start at 1, go to number + 1
8
-
n=n*i# let previous number times the current value of i
8
+
foriinrange(1, int(f)+1): # start at 1, go to number + 1
9
+
n=n*i# let answer = previous number times the current value of i, e.g 2 x 3, that answer x 4, so on
9
10
10
-
print(n)
11
+
defdigitSum(n):
12
+
currentPos=0
13
+
digits= []
14
+
digitSum=0
15
+
answer=str(n) # Stringify answer to make it loopable
16
+
17
+
# Loop through answer, add digits to list
18
+
fordigitinanswer:
19
+
currentNum=str(answer[currentPos]) # Current number = what's at the current position
20
+
digits.append(currentNum) # Add the number to the digit list
21
+
currentPos=currentPos+1# Go forward a position
22
+
23
+
# Loop through list of digits to get sum
24
+
fornumindigits:
25
+
digitSum=digitSum+int(num)
26
+
27
+
returndigitSum
28
+
29
+
30
+
print(str(f) +"! = "+str(n))
31
+
print("The sum of the digits of "+str(f) +"! is "+str(digitSum(n)))
0 commit comments