Mercurial > coderloop
view src/collatz.pl @ 0:307a81e46071 tip
initial committ
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Tue, 18 Oct 2011 01:17:49 -0700 |
parents | |
children |
line wrap: on
line source
1 #!/usr/bin/perl3 use bigint;4 $a = "/home/r/coderloop-test/euler14-a.in";5 $b = "/home/r/coderloop-test/euler14-b.in";7 sub read_integer{8 ##reads an integer from a file9 (my $file) = @_;10 my $int;11 open FILE, "<".$file or die $!;12 for (<FILE>){ chomp; /^\W*(\d+)\W*$/; $int = $1;}13 close FILE;14 return $int;}17 @collatz = (1);20 sub collatz_next {21 my $n = @_[0];22 if (1 == $n) {return 1;}23 if (0 == ($n % 2)){ return $n/2;}24 if (1 == ($n % 2)){ return (($n*3)+1);}25 }27 sub different_collatz_length {28 my $n = $_[0];29 my $d = 1;30 while ($n != 1){31 $d++;32 $n = collatz_next($n);}33 return $d;}35 sub collatz_length {36 ## calculate the length of the collatz sequence37 ## http://en.wikipedia.org/wiki/Collatz_conjecture38 ## starting at n39 my $n = @_[0];40 #print $n,"\n";41 #memoization42 #print "***** ", $collatz[$n], " ********\n";43 if (defined $collatz[$n]){return $collatz[$n];}44 if (1 == $n) {return 1;}45 if (0 == ($n % 2)){ return (1 + &collatz_length($n/2))}46 if (1 == ($n % 2)){ return (1 + &collatz_length(($n*3)+1));}47 }50 sub max_collatz {51 my $n = @_[0];52 my $max_length = 1;53 my $max_val = 1;54 for (my $i = 1; $i < $n; $i++){55 my $collatz = &different_collatz_length($i);56 #push(@collatz, $collatz);57 if ( $collatz >= $max_length){58 $max_length = $collatz ;59 $max_val = $i}}60 print "\n number is : $max_length --- ";61 print &collatz_length($max_val) . "\n";62 return $max_val;63 }68 if (defined @ARGV){69 print &max_collatz(read_integer($ARGV[0])), "\n";}