Matt Owen

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

return to portfolio
  1.  #!/usr/bin/perl
  2.  
  3.  use strict;
  4.  use warnings;
  5.  
  6.  
  7.  # sum of an array
  8.  sub sum {
  9.   my ($sum) = 0;
  10.   $sum += $_ for @_;
  11.   return $sum;
  12.  }
  13.  
  14.  
  15.  # file
  16.  open PRIMES, "primes_under_1000000.TXT" or die("PRIMES NOT FOUND.\n");
  17.  
  18.  
  19.  # init
  20.  my ($k, $sum, $max_length);
  21.  my (%primes) = map { chomp; int $_, $k++ } <PRIMES>;
  22.  my (@primes_list) = sort { $a <=> $b } keys %primes;
  23.  
  24.  
  25.  # compute the maximum length of a sequence to produce a prime under 10**6
  26.  $sum = 0;
  27.  while ($sum < 10**6) {
  28.   $sum += $primes_list[$max_length++];
  29.  }
  30.  
  31.  
  32.  #work
  33.  for my $p (reverse sort {$a <=> $b} keys %primes) {
  34.   for my $length (reverse 0..$max_length) {
  35.  
  36.   # ***
  37.   # start with the smallest value,
  38.   # because that's most likely to give us the
  39.   # longest sequence
  40.   for my $low (0..$max_length-$length) {
  41.  
  42.   # compute sum
  43.   $sum = sum @primes_list[$low..$low+$length];
  44.  
  45.  
  46.   # if it's prime, bingo, because
  47.   # we're working backwards from the longest
  48.   # imaginable sequence
  49.   if (defined $primes{$sum}) {
  50.   print "$sum";
  51.   goto LEAVE;
  52.   }
  53.   }
  54.   }
  55.  
  56.  }
  57.  
  58.  LEAVE: close PRIMES;