Skip to content

Instantly share code, notes, and snippets.

@Koitaro
Created January 4, 2012 09:12
Show Gist options
  • Select an option

  • Save Koitaro/1559227 to your computer and use it in GitHub Desktop.

Select an option

Save Koitaro/1559227 to your computer and use it in GitHub Desktop.
CHR : Project Euler 200-299
:- use_module(library(chr)).
:- chr_option(optimize, full).
:- chr_type list(T) ---> []; [T|list(T)].
:- chr_constraint
digit(+int),
num(+int,+list(int)),
answer(+int),
problem206.
problem206 <=> digit(9), num(1,[0]).
digit(N) ==> N > 0 | N1 is N-1, digit(N1).
answer(_) \ num(_,_) <=> true.
answer(_) \ digit(_) <=> true.
num(10,L) <=> check(10,L) | d2i(L,N), answer(N).
num(3,L) <=> \+ check(3,L) | true.
num(5,L) <=> \+ check(5,L) | true.
num(7,L) <=> \+ check(7,L) | true.
num(9,L) <=> \+ check(9,L) | true.
num(9,L) <=> num(10,[1|L]).
digit(D), num(N,L) ==> N < 9 | N1 is N+1, num(N1,[D|L]).
check(3,L) :- d2i(L,N), N1 is N*N, i2d(N1,L1), reverse(L1,L2), nth1(3,L2,9).
check(5,L) :- d2i(L,N), N1 is N*N, i2d(N1,L1), reverse(L1,L2), nth1(5,L2,8).
check(7,L) :- d2i(L,N), N1 is N*N, i2d(N1,L1), reverse(L1,L2), nth1(7,L2,7).
check(9,L) :- d2i(L,N), N1 is N*N, i2d(N1,L1), reverse(L1,L2), nth1(9,L2,6).
check(10,L) :-
d2i(L,N), N1 is N*N, i2d(N1,L1),
nth1(1,L1,1), nth1(3,L1,2), nth1(5,L1,3),
nth1(7,L1,4), nth1(9,L1,5).
d2i(L,X) :- d2i(L,0,X).
d2i([],X,X) :- !.
d2i([H|T],N,X) :- N1 is 10*N+H, d2i(T,N1,X).
i2d(N,X) :- i2d(N,[],X).
i2d(0,L,L) :- !.
i2d(N,L,X) :- N1 is N//10, N2 is N rem 10, i2d(N1,[N2|L],X).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment