Here is the problem I am trying to solve: Euler 20.
n!
meansn ⨉ (n - 1) ⨉ ... ⨉ 3 ⨉ 2 ⨉ 1
For example,
10! = 10 ⨉ 9 ⨉ ... ⨉ 3 ⨉ 2 ⨉ 1 = 3628800
, and the sum of the digits in the number10!
is3 + 6 + 2 + 8 + 8 + 0 + 0 = 27
.Find the sum of the digits in the number
100!
I have tried this:
y = 1 #The actual number
sum = 0 #The sum of its digits.
def factorial(x): #Calculates the number using a recursive factorial algorithm
global y
y = y*x
if x > 1:
factorial(x-1)
else:
return 0
factorial(100) #Calculate 100! and the function will put it in y.
def count(): #Calculates the sum.
global y, sum
while y > 0:
currentDigit = int(y) % 10 #Find the remainder of the number gives the very last digit
sum = sum + currentDigit #Add that to the total sum.
y = int(y) / 10 #Divide y by 10 knocking of the 1s-digit place and putting the 10s digit in its place.
return sum #return the sum.
print(count()) #print the count.
If I do factorial(10)
instead of 100 I get 27 which is what the problem says I should get, but I get 675 for factorial(100)
which the program says is wrong. What did I do wrong? I am not that familiar with Python, sorry if I made a stupid error.