Let’s have a look at problem number 20.
n! means n × (n − 1) × … × 3 × 2 × 1
For example, 10! = 10 × 9 × … × 3 × 2 × 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!
Well, it could have been soooo easy:
println(sum(digits(factorial(n))));
and we are done… however:
It seems like Julia uses look-up tables for factorials.
julia> factorial(100)
ERROR: OverflowError: 100 is too large to look up in the table
Stacktrace:
[1] factorial_lookup(::Int64, ::Array{Int64,1}, ::Int64) at ./combinatorics.jl:19
[2] factorial(::Int64) at ./combinatorics.jl:27
[3] top-level scope at none:0
Hence, we have to use a tiny workaround:
function parseARGS()
if isempty(ARGS)
n::UInt64 = 100;
else
n = tryparse(UInt64,ARGS[1])
end
return n
end
function main()
n = parseARGS();
println(sum(digits(factorial(big(n)))));
end
main()
$ julia ProjectEuler0020.jl 10
27
0.000058 seconds (71 allocations: 1.641 KiB)
$ julia ProjectEuler0020.jl 40
189
0.000054 seconds (434 allocations: 8.875 KiB)
$ julia ProjectEuler0020.jl 100
648
0.000109 seconds (1.43 k allocations: 31.141 KiB)
$ julia ProjectEuler0020.jl 1000
10539
0.002829 seconds (23.11 k allocations: 1.709 MiB)