Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: OT: Finding Factor Closest To Square Root

by BrowserUk (Patriarch)
on Feb 19, 2005 at 00:02 UTC ( [id://432575]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://432575]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-16 04:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found