#!/usr/bin/perl use warnings; use strict; use 5.010; # The 3n + 1 problem (http://www.streamtech.nl/problemset/100.html) my @pairs; say "Input:"; while () { if (/^[1-9]+\d*\s[1-9]+\d*$/) { # check for and prevent illegal entries chomp; push( @pairs, $_ ); } else { say "invalid input!" } } say "Output:"; foreach my $pair (@pairs) { my ( $first, $second ) = split( / /, $pair ); my $max_cycle_length = 0; if ( $first > $second ) { ( $first, $second ) = ( $second, $first ); } # doesn't matter whether the higher number is entered first or second foreach my $num ( $first .. $second ) { my $cycle_length_out = totalizer($num); if ( $cycle_length_out > $max_cycle_length ) { $max_cycle_length = $cycle_length_out; } } say "$first $second $max_cycle_length"; } sub totalizer { my $number = shift; my $current_cycle_length; for ( $current_cycle_length = 1 ; $number != 1 ; ++$current_cycle_length ) { if ( $number % 2 != 0 ) { $number = ( $number * 3 + 1 ); } else { $number /= 2; } } return $current_cycle_length; }