# Euler Solution 20

### From ProgSoc Wiki

## Contents |

# Solutions for Problem 20

Find the sum of digits in 100! = 100 x 99 x 98 x .... x 2 x 1

## Lisp by SanguineV

Runtime (script mode): 42.9ms

(define (sumdigit n) (if (> n 9) ((lambda (rem) (+ rem (sumdigit (/ (- n rem) 10)))) (modulo n 10)) n)) (define (fact n) (if (= n 1) 1 (* n (fact (- n 1))))) (begin (display (sumdigit (fact 100))) (newline)) (exit)

## Python by Althalus

Runtime: 14 ms

import time start_time = time.time() prev,next,num=1,2,0 while next <=100: prev*=next next+=1 for c in str(prev): num+=int(c) print(num) run_time = time.time() - start_time print (run_time)

## Excel VBA by mmaster

Note: This is untested; I'm not sure if the algorithm works. There doesn't seem to be any way to get Excel to display more than 15 significant digits (no, I don't think Excel (or OpenOffice Calc - which this code will run in, unchanged, BTW - for that matter) can store 100! directly. But otherwise, this algorithm is correct; it handles smaller factorials without a problem - tom)

Sub ProblemTwenty() Dim Limit As Integer Limit = 100 Dim Total Total = 1 Dim SumOfDig SumOfDig = 0 Dim strTotal As String ' get the factorial For i = 2 To Limit Total = Total * i Next i ' get the sum of digits strTotal = Str(Total) For j = 1 To Len(strTotal) SumOfDig = SumOfDig + Val(Mid$(strTotal, j, 1)) Next j MsgBox SumOfDig End Sub

## Ruby by ctd

Runtime: 10ms

def sumOfDigits(num) if num < 10 return num else return (num % 10) + sumOfDigits(num / 10) end end puts sumOfDigits(100.downto(1).inject(:*));