Truncatable primes: Difference between revisions
Content deleted Content added
Added Racket version |
|||
Line 1,166: | Line 1,166: | ||
}; |
}; |
||
[left(6),right(6)]</lang> |
[left(6),right(6)]</lang> |
||
=={{header|Perl}}== |
|||
<lang perl>#!/usr/bin/perl |
|||
use warnings; |
|||
use strict; |
|||
use constant { |
|||
LEFT => 0, |
|||
RIGHT => 1, |
|||
}; |
|||
{ my @primes = (2, 3); |
|||
sub is_prime { |
|||
my $n = shift; |
|||
return if $n < 2; |
|||
for my $prime (@primes) { |
|||
last if $prime >= $n; |
|||
return if 0 == $n % $prime; |
|||
} |
|||
my $sqrt = sqrt $n; |
|||
while ($primes[-1] < $sqrt) { |
|||
my $new = 2 + $primes[-1]; |
|||
$new += 2 until is_prime($new); |
|||
push @primes, $new; |
|||
return if 0 == $n % $new; |
|||
} |
|||
return 1; |
|||
} |
|||
} |
|||
sub trunc { |
|||
my ($n, $side) = @_; |
|||
my $regex = $side == LEFT ? qr/^./ : qr/.$/; |
|||
$n =~ s/$regex//; |
|||
return $n; |
|||
} |
|||
sub is_tprime { |
|||
my ($n, $side) = @_; |
|||
return if $n =~ /0/; |
|||
return (is_prime($n) and (1 == length $n or is_tprime(trunc($n, $side), $side))); |
|||
} |
|||
my $length = 6; |
|||
my @tprimes = ('9' x $length) x 2; |
|||
for my $side (LEFT, RIGHT) { |
|||
$tprimes[$side] -= 2 until is_tprime($tprimes[$side], $side); |
|||
} |
|||
print 'left ', join(', right ', @tprimes), "\n";</lang> |
|||
{{out}} |
|||
<pre>left 998443, right 739399</pre> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |