Matt Owen

source code for "files/pe/pe_035.pl"

return to portfolio
  1.  #!/usr/bin/perl
  2.  
  3.  use strict;
  4.  use warnings;
  5.  
  6.  
  7.  # rotates a string
  8.  sub rotate {
  9.   my @s = split //, shift;
  10.   push @s, shift(@s);
  11.   return join '', @s;
  12.  }
  13.  
  14.  
  15.  # open file handle
  16.  open(PRIMES, "primes_under_1000000.TXT") or die("CAN'T OPEN FILE.");
  17.  
  18.  
  19.  # init
  20.  my %primes;
  21.  my ($n, $qprimes);
  22.  my $count = 0;
  23.  
  24.  
  25.  # make sure they're ints and have no new lines
  26.  for (<PRIMES>) {
  27.   chomp;
  28.   $primes{int $_} = 1;
  29.  }
  30.  
  31.  
  32.  # brute force - can be slightly optimized by incrementing count by
  33.  # length of the circular prime (then removing all occurences from %primes)
  34.  for (keys %primes) {
  35.   $n = $_;
  36.   $qprimes = 0;
  37.  
  38.   for (1..length $n) {
  39.   $qprimes++ if defined $primes{$n};
  40.   $n = rotate $n;
  41.   }
  42.  
  43.   $count++ if $qprimes == length $n;
  44.  }
  45.  
  46.  
  47.  print $count;