All,
YuckFoo has posted on a lot of interesting problems. I was looking at
Rotationally Prime Numbers and doubted any mathematical shortcuts could be employed to determine if a candidate number passed since prime numbers are involved. I pulled out my bag of tricks to make the brute force method faster and found
60 55 rotational primes in less than 1 second:
#!/usr/bin/perl
use strict;
use warnings;
my $impossible = qr/([245680])/;
my $n = 5;
print "$_\n" for (2, 3, 5);
for ( 1 .. 3_157 ) {
$n += 2;
my $skip;
if ( $n =~ $impossible ) {
$skip = adjust( $1, $n );
next if $skip && $n =~ $impossible;
}
print $n, "\n" if rot_prime( $n );
next if $skip;
$n += 4;
if ( $n =~ $impossible ) {
adjust( $1, $n );
next if $n =~ $impossible;
}
print $n, "\n" if rot_prime( $n );
}
print "Last number checked : $n\n";
sub rot_prime {
my $n = shift;
return 0 if ! is_prime( $n );
my @dig = split //, $n;
for ( 1 .. $#dig ) {
push @dig, shift @dig;
return 0 if ! is_prime( join '', @dig );
}
return 1;
}
sub adjust {
my $dig = shift;
return 0 if $dig == 5 && $_[0] =~ /5$/;
my $new = $dig;
$new += $dig == 5 ? 2 : 1;
$_[0] =~ s/$dig(\d+)$/$new . '1' x length( $1 )/e;
$_[0] = $_[0] - $_[0] % 3;
$_[0] += not ($_[0] % 2) ? -1 : 2;
return $_[0];
}
sub is_prime {
my $num = shift;
my ($div, $sqrt) = (5, int sqrt $num);
while ( $div <= $sqrt ) {
return 0 if not $num % $div;
$div += 2;
return 0 if not $num % $div;
$div += 4;
}
return 1;
}
The problem is that I can't find any after 999331 even though I tested numbers in the hundreds of millions. It is possible that my code is flawed or perhaps it is the last one.
Can you find any more or prove that there aren't any? Note: This code does not supress rotations.
Update: Minor bugfix to avoid multiples of 3
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.