Maybe one of the mathematician's will show me the error of my ways, but I think that the prime factors thing is a red-herring.
The following brute force approach works quite quickly for numbers up to about 12 or 13 digits, usually much more quickly that it takes M::B::F to find the prime factors.
If you're looking to do this with very large numbers (as suggested by your use of Math::Big), then your probably in for a long wait either way. If the number in question is itself prime, then the nearest factor to the square root will be 1. That means you have to add 1 to list that factor_wheel() produces before you start doing your combinatorics, and it's presence just slows the search to what effectively amounts to a linear search anyway.
#! perl -slw use strict; my $NUM = $ARGV[ 0 ] || die 'No arg'; my $root = sqrt( $NUM ); my( $lo, $hi ) = ( int( $root ), int( $root + 1 ) );; $lo-- while $NUM % $lo; $hi++ while $NUM % $hi; my $near = ( $lo, $hi )[ abs( $root - $lo ) > abs( $root - $hi ) ]; print "$NUM ($root) : $near";
In reply to Re: OT: Finding Factor Closest To Square Root
by BrowserUk
in thread OT: Finding Factor Closest To Square Root
by QM
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |