Prolog: Project Euler - Problem 39

If p is the perimeter of a right angle triangle, {a, b, c}, which value, for p ≤ 1000, has the most solutions?

原始ピタゴラス数の行列による生成をライブラリ化。

:- module(pythagoreans_triangle,[root_triangle/1,prim_gen/2]).

root_triangle([3,4,5]).

prim_gen([A,B,C],L) :- mul([-A,B,C],L); mul([-A,-B,C],L); mul([A,-B,C],L).

mul([A,B,C],[X,Y,Z]) :- X is -A-2*B+2*C, Y is -2*A-B+2*C, Z is -2*A-2*B+3*C.

これを使ってProblem 39。

:- use_module(library(pythagoreans_triangle),[root_triangle/1,prim_gen/2]).

problem39(Answer) :- aggregate(max(Len,N),solve(N,Len),max(_,Answer)).

solve(N,Len) :- bagof(L,triangle(N,L),X), length(X,Len).

triangle(Length,L2) :-
    root_triangle(L), primitive(L,L1),
    sumlist(L1,Sum), Max is 1000//Sum, between(1,Max,N),
    mul(L1,N,L2), sumlist(L2,Length).

mul([],_,[]).
mul([H|T],N,[H1|X]) :- H1 is H*N, mul(T,N,X).

primitive(L,X) :- check(L) -> (X = L; prim_gen(L,L1), primitive(L1,X)).

check(L) :- sumlist(L,N), N =< 1000.

Notes

  1. koitaro posted this