Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 466499f

Browse files
sum of digits working
1 parent c315c58 commit 466499f

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

‎4-FactorialDigitSum.py‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,31 @@
11
# 4 - Factorial Digit Sum
22
# 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!
33

4-
f = 10 # Factorial number = 10
4+
print("Factorial & Digit Sum Calculator")
5+
f = input("Enter a number: ")
56
n = 1 # start at 1
67

7-
for i in range(1, f + 1): # start at 1, go to number + 1
8-
n = n * i # let previous number times the current value of i
8+
for i in range(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
910

10-
print(n)
11+
def digitSum(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+
for digit in answer:
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+
for num in digits:
25+
digitSum = digitSum + int(num)
26+
27+
return digitSum
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /