Mercurial > coderloop
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:307a81e46071 |
---|---|
1 #!/usr/bin/perl | |
2 | |
3 use bigint; | |
4 $a = "/home/r/coderloop-test/euler14-a.in"; | |
5 $b = "/home/r/coderloop-test/euler14-b.in"; | |
6 | |
7 sub read_integer{ | |
8 ##reads an integer from a file | |
9 (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;} | |
15 | |
16 | |
17 @collatz = (1); | |
18 | |
19 | |
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 } | |
26 | |
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;} | |
34 | |
35 sub collatz_length { | |
36 ## calculate the length of the collatz sequence | |
37 ## http://en.wikipedia.org/wiki/Collatz_conjecture | |
38 ## starting at n | |
39 my $n = @_[0]; | |
40 #print $n,"\n"; | |
41 #memoization | |
42 #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 } | |
48 | |
49 | |
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 } | |
64 | |
65 | |
66 | |
67 | |
68 if (defined @ARGV){ | |
69 print &max_collatz(read_integer($ARGV[0])), "\n";} |