source code for "files/pe/pe_014.pl"
return to portfolio
- #!/usr/bin/perl
- # should use dynamic programming to solve this... but... this problem's not worth it
- use strict;
- use warnings;
- sub collatz {
- my $n = shift;
- my ($y, $count) = (0, 1);
- while ($n != 1) {
- $n = $n % 2 == 0 ? $n/2 : 3*$n+1;
- push(@lis, $n);
- $count++;
- }
- return int $count;
- }
- my ($largest, $c, $k, $final);
- for $k (5..1000000) {
- $c = collatz($k);
- if ($c > $largest) {
- $largest = $c;
- $final = $k;
- }
- }
- print $final;