my @num = ( 3, 7, 11 ); my @den = ( 5, 12, 19 ); # get prime factors (you have to write this yourself :) # it returns the list of prime factors for each argument my @num_fac = get_prime_factors_list( 2..\$num[-1] ); my @den_fac = get_prime_factors_list( 2..\$den[-1] ); @num_fac = sort { \$a <=> \$b } @num_fac; @den_fac = sort { \$a <=> \$b } @den_fac; # modified merge sort my \$n, \$d; while (( \$n < \$#num_fac ) and ( \$d < \$#den_fac )) { if ( \$num_fac[\$n] == \$den_fac[\$d] ) { # drop both \$n++; \$d++; } elsif ( \$num_fac[\$n] < \$den_fac[\$d] ) { push @num_fin, \$num_fac[\$n]; \$n++; } else { push @den_fin, \$den_fac[\$d]; \$d++; } } # any remaining factors are not shared push @num_fin, @num_fac[\$n..\$#num_fac]; push @den_fin, @den_fac[\$d..\$#den_fac]; # edge cases @num_fin = (1) unless @num_fin; @den_fin = (1) unless @den_fin; # carefully multiply and divide my \$q = shift @num_fin; while ( @num_fin and @den_fin ) { if ( \$q > 1 ) { \$q = \$q / (shift @den_fin); } if ( \$q < 1 ) { \$q = \$q * (shift @num_fin); } } # only one of these will be true: \$q = \$q * (shift @num_fin) while @num_fin; \$q = \$q / (shift @den_fin) while @den_fin;