in reply to OT: Finding Factor Closest To Square Root
Not sure if this is correct either, but I checked a few cases and it appears to work. Is there a good method of verification?
It starts to get slow with big numbers, but it's much quicker than factors_wheel() finding the prime factors, for all the cases I tried.
There appears to be a bug in the overloading in Math::Big, hence the de-Bignumming map.
Update: Version 3. Anyone care to break this one for me?
Don't
>#! perl -slw use strict; use overload; use Math::Big::Factors qw[ factors_wheel ]; use List::Util qw[ reduce min ]; use Algorithm::Loops qw[ NestedLoops ]; my $NUM = $ARGV[ 0 ] || 996; my $root = sqrt $NUM; my @pfs = reverse map{ "$_" } factors_wheel( $NUM ); print "$NUM primefactors ( @pfs )"; my $n = 0; while( $root <= reduce{ $a * $b } @pfs ) { my $near = reduce{ ( $a * $b ) <= $root ? $a*$b : 0+$a } @pfs; $n = $near if abs( $root - $near ) < abs( $root - $n ); $n = $near * $pfs[ -1 ] if abs( $root - $n ) > ( $near * $pfs[ -1 ] - $root ); my $discard = shift @pfs; next if $pfs[ 0 ] == $discard; unshift @pfs, $pfs[0] while $root > reduce{ $a * $b } @pfs; } print "$NUM ($root} : $n"; __END__ P:\test>432558 996 primefactors ( 83 3 2 2 ) 996 (31.559467676119} : 36 P:\test>432558 1000 1000 primefactors ( 5 5 5 2 2 2 ) 1000 (31.6227766016838} : 32 P:\test>432558 100000000000000 100000000000000 primefactors ( 5 5 5 5 5 5 5 5 5 5 5 5 5 5 2 2 2 2 2 2 + 2 2 2 2 2 2 2 2 ) 100000000000000 (10000000} : 10000000 P:\test>432558 10000000000000 10000000000000 primefactors ( 5 5 5 5 5 5 5 5 5 5 5 5 5 2 2 2 2 2 2 2 +2 2 2 2 2 2 ) 10000000000000 (3162277.66016838} : 3125000 P:\test>432558 1995 1995 primefactors ( 19 7 5 3 ) 1995 (44.6654228682546} : 35
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: OT: Finding Factor Closest To Square Root
by sleepingsquirrel (Chaplain) on Feb 19, 2005 at 16:03 UTC | |
by BrowserUk (Patriarch) on Feb 19, 2005 at 16:12 UTC | |
by BrowserUk (Patriarch) on Feb 19, 2005 at 16:35 UTC | |
by sleepingsquirrel (Chaplain) on Feb 19, 2005 at 17:15 UTC | |
by BrowserUk (Patriarch) on Feb 19, 2005 at 20:11 UTC |