in reply to OT: Finding Factor Closest To Square Root
Doesn't use Math::Big::Factor, isn't particularly dynamic, doesn't have exponential complexity, and could be much faster in C. With all those caveats, here you go...
-- All code is 100% tested and functional unless otherwise noted.
#!/usr/bin/perl -w use strict; print sqrt_factor(shift), "\n"; sub sqrt_factor { my $n = shift; my $root = int(sqrt($n)); for (my $i=$root; $i>1; $i--) { if( ($n % $i) == 0 ) { my $factor2 = int($n / $i); return (($root - $i)<($factor2 - $root)) ? $i : $factor2 } } return 1; }
-- All code is 100% tested and functional unless otherwise noted.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: OT: Finding Factor Closest To Square Root
by QM (Parson) on Feb 20, 2005 at 07:20 UTC |
In Section
Seekers of Perl Wisdom