in reply to OT: Finding Factor Closest To Square Root

Update: Ignore this, it doesn't work.

You'll have tp pretend that I have M::B::F::f_w().. CPAN's being boring.

#! perl -slw use strict; use List::Util qw[ reduce ]; my $root = sqrt 1000; my @pfs = ( 2, 2, 2, 5, 5, 5 ); my $near = reduce{ $a * $b < $root ? $a*$b : $a } reverse @pfs; print +( $root - $near ) < ( $near * $pfs[0] - $root ) ? $near : $near * $pfs[0];

Examine what is said, not who speaks.
Silence betokens consent.
Love the truth but pardon error.

Replies are listed 'Best First'.
Re^2: OT: Finding Factor Closest To Square Root
by Roy Johnson (Monsignor) on Feb 19, 2005 at 00:23 UTC
    I rearranged it a bit so you can just plug in your factor list and it will figure out what your number is. Note that in this case, the closest value is 5*7, but it returns 3*19.
    use strict; use warnings; use List::Util qw[ reduce ]; my @pfs = ( 3,5,7,19 ); my $num = reduce { $a * $b } @pfs; my $root = sqrt $num; print "N=$num, R=$root\n"; #the rest is the same as you had it
    Here's a fix:
    use strict; use warnings; use List::Util qw[ reduce ]; my @pfs = ( 3,5,7,19 ); my $num = reduce { $a * $b } @pfs; my $root = sqrt $num; print "N=$num, R=$root\n"; my $near = reduce{ abs($root - $a * $b) < abs($root - $a) ? $a*$b : $a } reverse @pfs; print abs($root - $near) > abs($root - ($num/$near)) ? $num/$near : $near ;

    Caution: Contents may have been coded under pressure.

      One testcase was never going to hack it. I should have thought of your method, but I was too busy trying to figure out why CPAN would install M::B::F.


      Examine what is said, not who speaks.
      Silence betokens consent.
      Love the truth but pardon error.
        Mine isn't perfect, either. Try 2,2,2,7,19,19, for example. I'm pretty sure the problem requires an exhaustive search of all combinations.

        Caution: Contents may have been coded under pressure.