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 strict;
use warnings;
use feature 'say';
use List::Util 'min';
use ntheory 'is_prime';
 
sub rotate { my($i,@a) = @_; join '', @a[$i .. @a-1, 0 .. $i-1] }
 
sub isCircular {
    my ($n) = @_;
    return 0 unless is_prime($n);
    my @circular = split //, $n;
    return 0 if min(@circular) < $circular[0];
    for (1 .. scalar @circular) {
        my $r = join '', rotate($_,@circular);
        return 0 unless is_prime($r) and $r >= $n;
    }
    1
}
 
say "The first 19 circular primes are:";
for ( my $i = 1, my $count = 0; $count < 19; $i++ ) {
    ++$count and print "$i " if isCircular($i);
}
 
say "\n\nThe next 4 circular primes, in repunit format, are:";
for ( my $i = 7, my $count = 0; $count < 4; $i++ ) {
    ++$count and say "R($i)" if is_prime 1 x $i
}
 
say "\nRepunit testing:";
 
for (5003, 9887, 15073, 25031, 35317, 49081) {
    say "R($_): Prime? " . (is_prime 1 x $_ ? 'True' : 'False');
}