Problem20

30分プログラム、その286。Problem20 via Project Euler

n × (n - 1) × ... × 3 × 2 × 1 を n! と表す。
100! の各桁の数字の合計を求めよ。

桁の分解といえば、unfold。Erlangの標準ライブラリには無いので、Ruminations of a Programmer: Fun with unfold in Erlangを参考に自分で作った。

使い方

$ escript problem20.erl 100
648

ソースコード

-module(problem20).
-export([main/1]).

unfold(Pred,Trans,Inc,Seed) ->
    case Pred(Seed) of
	true -> [Trans(Seed)|unfold(Pred,Trans,Inc,Inc(Seed))];
	_ -> []
    end.

fact(1) -> 1;
fact(N) -> N * fact(N-1).
    
split(X)->
    unfold(fun(N)->N=/=0 end,
	   fun(N)->N rem 10 end,
	   fun(N)->N div 10 end,
	   X).

main([X])-> io:format("~p~n",[lists:sum(split(fact(list_to_integer(X))))]).