読者です 読者をやめる 読者になる 読者になる

project euler problem 6-7 answer

解いた。5は手で解いてしまったので飛ばす。

sum_sub(N, M, Acc, Sum) :-
        N1 is N + 1,
        Acc1 is N + Acc,
        sum_sub(N1, M, Acc1, Sum).

square_sum(N, M, Sum) :- square_sum_sub(N, M, 0, Sum).
square_sum_sub(M, M, Acc, Sum) :- Sum is Acc + M * M.
square_sum_sub(N, M, Acc, Sum) :-
        N1 is N + 1,
        Acc1 is Acc + N * N,
        square_sum_sub(N1, M, Acc1, Sum).

problem6(Result) :-
        sum(1, 100, Sum),
        square_sum(1, 100, SquareSum),
        Result is Sum * Sum - SquareSum.

not_divide_by(N, [Head | Rest]) :- N mod Head =\= 0, !, not_divide_by(N, Rest).
not_divide_by(_, []).

% N番目の素数を見つける
primes(N, NthPrime) :- primes_sub(N, NthPrime, [], 2).
primes_sub(0, NthPrime, [NthPrime | _], _).
primes_sub(N, NthPrime, Primes, Current) :-
        Next is Current + 1,
        N1 is N - 1,
        (not_divide_by(Current, Primes) ->
         primes_sub(N1, NthPrime, [Current | Primes], Next);
         primes_sub(N, NthPrime, Primes, Next)).

problem7(R) :- primes(10001,R).