Matt Owen

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

return to portfolio
  1.  #!/usr/bin/perl
  2.  
  3.  # should use dynamic programming to solve this... but... this problem's not worth it
  4.  
  5.  use strict;
  6.  use warnings;
  7.  
  8.  sub collatz {
  9.   my $n = shift;
  10.   my ($y, $count) = (0, 1);
  11.  
  12.   while ($n != 1) {
  13.   $n = $n % 2 == 0 ? $n/2 : 3*$n+1;
  14.   push(@lis, $n);
  15.   $count++;
  16.   }
  17.  
  18.   return int $count;
  19.  }
  20.  my ($largest, $c, $k, $final);
  21.  
  22.  for $k (5..1000000) {
  23.   $c = collatz($k);
  24.  
  25.   if ($c > $largest) {
  26.   $largest = $c;
  27.   $final = $k;
  28.   }
  29.  }
  30.  
  31.  print $final;