Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Nov 5th, 2011  |  syntax: None  |  size: 0.67 KB  |  views: 34  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #!/usr/bin/perl
  2.  
  3. use v5.12;
  4. use strict;
  5. use warnings;
  6.  
  7. my @max     = qw/0 0/;
  8. my %results = {
  9.     1 => 0,
  10.     2 => 1,
  11. };
  12.  
  13. sub chainLength {
  14.  
  15.     my $arg   = shift;
  16.     my $num   = $arg;
  17.     my $count = 0;
  18.  
  19.     while ( $num > 2 ) {
  20.         if ( exists $results{$num} ) {
  21.             return ( $results{$arg} = $count + int( $results{$num} ) );
  22.         }
  23.  
  24.         ( ( $num % 2 ) == 0 ) ? ( $num /= 2 ) : ( $num = 3 * $num + 1 );
  25.         $count++;
  26.     }
  27.     return ( $results{$arg} = $count );
  28. }
  29.  
  30. for my $i ( 2 .. 1000000 ) {
  31.     my $res = chainLength($i);
  32.     if ( $res > $max[1] ) {
  33.  
  34.         $max[0] = $i;
  35.         $max[1] = $res;
  36.     }
  37.  
  38. }
  39. print "@max";
  40.  
clone this paste RAW Paste Data