use strict; my @nineset = (9, 8, 7, 6, 5, 4, 3, 2, 1); my @tenset = (9, 8, 7, 6, 5, 4, 3, 2, 1, 0); # Array is arranged: # a b c # d e f # g h i sub gcf { my ($x, $y) = @_; ($x, $y) = ($y, $x % $y) while $y; return $x; } sub multigcf { my $x = shift; $x = gcf($x, shift) while @_; return $x; } my ($a, $b, $c, $d, $e, $f, $g, $h, $i); my ($abc, $def, $ghi, $adg, $beh, $cfi); my ($gcf1, $gcf2, $gcf3, $gcf4); my $maxgcf = 1; my @maxsolution = (); foreach $a (@nineset) { foreach $b (@nineset) { foreach $c (@nineset) { foreach $d (@nineset) { foreach $g (@nineset) { $abc = $a . $b . $c; $adg = $a . $d . $g; next if ($abc eq $adg); $gcf1 = gcf($abc, $adg); next if ($gcf1 <= $maxgcf || $gcf1 == 1); foreach $e (@tenset) { foreach $f (@tenset) { $def = $d . $e . $f; next if ($abc eq $def || $adg eq $def); $gcf2 = multigcf($def, $abc, $adg); next if ($gcf2 <= $maxgcf || $gcf2 == 1); foreach $h (@tenset) { $beh = $b . $e . $h; next if ($abc eq $beh || $adg eq $beh || $def eq $beh); $gcf3 = multigcf($beh, $def, $abc, $adg); next if ($gcf3 <= $maxgcf || $gcf3 == 1); foreach $i (@tenset) { $cfi = $c . $f . $i; next if ($abc eq $cfi || $adg eq $cfi || $def eq $cfi || $beh eq $cfi); $ghi = $g . $h . $i; next if ($abc eq $ghi || $adg eq $ghi || $def eq $ghi || $beh eq $ghi || $cfi eq $ghi); $gcf4 = multigcf($cfi, $ghi, $beh, $def, $abc, $adg); next if ($gcf4 <= $maxgcf || $gcf4 == 1); # Found a good one so far. $maxgcf = $gcf4; @maxsolution = ($a, $b, $c, $d, $e, $f, $g, $h, $i); } # i } #h } #f } #e } #g } # d } #c } #b } #a ($a, $b, $c, $d, $e, $f, $g, $h, $i) = @maxsolution; print "$a $b $c\n"; print "$d $e $f\n"; print "$g $h $i\n"; print "Common divisor is: $maxgcf\n";