Here's a recursive solution to find the closest set of factors to a target (with wrapper script). I think it's solid.
use strict;
use warnings;
use List::Util qw[ reduce ];
my @pfs = ( 2,3,3,3,7, 997 );
my $num = reduce { $a * $b } @pfs;
my $root = sqrt $num;
print "N=$num, R=$root\n";
sub closest {
# Args are target and factor-list
my ($target, $car, @cdr) = @_;
@cdr or return $car;
reduce { abs($target - $a) < abs($target - $b) ? $a : $b }
($car*closest($target/$car, @cdr), closest($target, @cdr), $c
+ar);
}
print closest($root, @pfs), "\n";
Caution: Contents may have been coded under pressure.
|