Skip to content

Instantly share code, notes, and snippets.

@lithp
Created April 9, 2015 15:19
Show Gist options
  • Select an option

  • Save lithp/210f0dfa3c8b949d5d05 to your computer and use it in GitHub Desktop.

Select an option

Save lithp/210f0dfa3c8b949d5d05 to your computer and use it in GitHub Desktop.
Euler 35 in prolog
#!/usr/bin/swipl -q -t does_not_work -s
divides(X, Y) :- 0 is X mod Y.
prime(X) :- X > 1,
Limit is floor(sqrt(X)),
foreach(between(2, Limit, Factor), not(divides(X, Factor))).
rotate([H | Rest], R) :- append(Rest, [H], R).
rotations(List, Rotations) :- length(List, Length),
rotations(Length, List, Rotations).
rotations(1, List, [Rotation]) :- rotate(List, Rotation), !.
rotations(N, List, [Rotation | Rest]) :- Next is N - 1,
rotate(List, Rotation),
rotations(Next, Rotation, Rest).
int_rotations(X, Rotations) :- number_chars(X, Chars),
rotations(Chars, CharRotations),
maplist(number_chars, Rotations, CharRotations), !.
cyclic_prime(X) :- int_rotations(X, Rotations),
maplist(prime, Rotations), !.
cyclic_primes(0, []).
% cyclic_primes(N, _) :- 0 is N mod 1000, writeln(N), false.
cyclic_primes(N, [N | Rest]) :- cyclic_prime(N),
Next is N-1, cyclic_primes(Next, Rest).
cyclic_primes(N, Primes) :- not(cyclic_prime(N)),
Next is N - 1, cyclic_primes(Next, Primes).
% does_not_work :- trace, cyclic_primes(1000000, Primes),
does_not_work :- cyclic_primes(1000000, Primes),
length(Primes, Count),
writeln(Count).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment