Skip to content

Instantly share code, notes, and snippets.

@Koitaro
Created July 19, 2011 09:18
Show Gist options
  • Select an option

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

Select an option

Save Koitaro/1091808 to your computer and use it in GitHub Desktop.
CHR : Project Euler 120-129
:- use_module(library(chr)).
:- chr_option(optimize, full).
:- chr_type list(T) ---> []; [T|list(T)].
:- chr_constraint
num(+int,+int), num(+int), sum(+int), answer(+int),
i2d(+int,+list(int),-list(int)),
palindrome(+int), sq_sum(+int,-int), problem125.
problem125 <=> sqrt(10**8//2,N), floor(N,N1), N2 is N1-2, num(N1,N2), sum(0).
num(M,N) ==> M =:= N+2, N >= 0 | M1 is M-1, N1 is N-1, num(M1,N1).
num(M,N) <=> N >= 0, sq_sum(M,A), sq_sum(N,B), X is A-B, X < 10**8 |
num(X), N1 is N-1, num(M,N1).
num(_,_) <=> true.
num(N) <=> palindrome(N) | answer(N).
num(_) <=> true.
answer(N) \ answer(N) <=> true.
sum(M), answer(N) <=> X is M+N, sum(X).
i2d(0,L,X) <=> X = L.
i2d(N,L,X) <=> N1 is N//10, N2 is N rem 10, i2d(N1,[N2|L],X).
palindrome(N) <=> i2d(N,[],L), reverse(L,L).
sq_sum(N,X) <=> X is N*(N+1)*(2*N+1)//6.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment