Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.

For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.

Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.



A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.

For example:
R(2) = 11 and R(5) = 11111 are repunits.



Task
 Find the first 19 circular primes.


 If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.


 (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.


See also
 Wikipedia article - Circular primes.
 Wikipedia article - Repunit.
 OEIS sequence A016114 - Circular primes.


 
?- use_module(library(primality)).
 
circular(N) :- member(N, [2, 3, 5, 7]).
circular(N) :-
    limit(15, (
        candidate(N),
        N > 9,
        circular_prime(N))).
circular(r(K)) :-
    between(6, inf, K),
    N is (10**K - 1) div 9,
    prime(N).
 
candidate(0).
candidate(N) :-
    candidate(M),
    member(D, [1, 3, 7, 9]),
    N is 10*M + D.
 
circular_prime(N) :-
    K is floor(log10(N)) + 1,
    circular_prime(N, N, K).
circular_prime(_, _, 0) :- !.
circular_prime(P0, P, K) :-
   P >= P0,
   prime(P),
   rotate(P, Q), succ(DecK, K),
   circular_prime(P0, Q, DecK).
 
rotate(N, M) :-
    D is floor(log10(N)),
    divmod(N, 10, Q, R),
    M is R*10**D + Q.
 
main :-
    findall(P, limit(23, circular(P)), S),
    format("The first 23 circular primes:~n~w~n", [S]),
    halt.
 
?- main.
 