note
QM
There are better ways to compute factorial quotients without overflow or loss of precision. But I won't go into that here. Instead I'll address the problem you stated originally.
<p>
After examining all of the replies to date, it seems you want to reduce the quotient. Since you're dealing with large numbers (products of factorials), reducing it won't be so easy. Here's a school-boy method that just relies on breaking the process down into steps, nothing fancy:
<p>
First in pseudo-code:
<blockquote>
1) Factor each term in the numerator and denominator into its prime factors. (Since these are factorials, this is pretty quick).<p>
2) Collect all of the numerator factors into one array, and all of the denominator factors in another array.<p>
3) Sort both arrays.<p>
4) Do a modified merge sort to cancel like terms in both arrays. Keep any terms that don't have a match in the other array.<p>
5) You can compute the quotient to a high degree of accuracy without overflowing or underflowing by judicious choices in the next term to grab.
</blockquote>
Now let's see if I can do this in code (untested):
<blockquote><code>
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;
</code></blockquote>
You can probably improve this considerably. For instance, instead of keeping each prime factor (including duplicates), only keep a count.
<div class="pmsig"><div class="pmsig-294463">
<p>-QM<br />
--<br />
Quantum Mechanics: The dreams stuff is made of
</div></div>
481987
481987