tree(X,[X|Xs]-Xs). tree(S,[X|Xs]-Zs) :- S0 is S - X, tree(S0,Xs-Ys), tree(S0,Ys-Zs). okay(Xs,S,_) :- tree(S,Xs-[]). okay(Xs,S,[Y|Ys]) :- S1 is S + Y, okay(Xs,S1,Ys). determine(Xs,R) :- ( okay(Xs,0,Xs) -> R = yes ; R = no ). getNumber(F,N0,N) :- get_code(F,C), ( C < 48 -> N = N0 ; C > 57 -> N = N0 ; N1 is N0 * 10 + C - 48, getNumber(F,N1,N) ). getNumber(F,N) :- getNumber(F,0,N). getNumbers(F,0,[]). getNumbers(F,N,[X|Xs]) :- getNumber(F,X), N0 is N - 1, getNumbers(F,N0,Xs). main(F) :- getNumber(F,N), ( N == 0 -> close(F) ; getNumbers(F,N,Xs), determine(Xs,R), format('~w~n',[R]), main(F) ). main :- open('balance.in',read,F), main(F).