use strict; use warnings; use bigint; # How high a number are you willing to factorialize? my $factorial_limit = 999; # Pre-cache them to save on calls my @factorials = do { my $last_fact = 1; (0, 1, map { $last_fact *= $_ } 2..$factorial_limit) }; # What's the biggest number you want to print? my $print_up_to = 200; # Each element of @formulas is an an op-string: # a string of Fs and Ss, indicating factorial # and square root, in order applied to get the # index my %formulas = (3 => '3'); my @unapplied = ([3, '3']); while (@unapplied) { my ($v, $ops) = @{shift(@unapplied)}; # Apply factorial if ($v <= $factorial_limit) { my $fv = $factorials[$v]; my $fops = $ops . 'F'; if (not exists $formulas{$fv}) { push @unapplied, [$fv, $fops]; $formulas{$fv} = $fops; } } # Apply sqrt $v = int(sqrt($v)); $ops .= 'S'; if (not exists $formulas{$v}) { push @unapplied, [$v, $ops]; $formulas{$v} = $ops; } } for (sort { $a <=> $b } keys %formulas) { last if $_ > $print_up_to; print "$_: $formulas{$_}\n"; }