Haskell.
cartesianWith f xs = concatMap $ \y -> map (`f` y) xs
factorsOfPrimeFactorization =
foldl (cartesianWith (*)) [1] . map (\(p, e) -> map (p^) [0..e])
> factorsOfPrimeFactorization [(2, 3), (3, 1)]
[1, 2, 3, 4, 6, 8, 12, 24]
为了对结果进行排序,
import Data.List
cartesianWith f xs = concatMap $ \y -> map (`f` y) xs
factorsOfPrimeFactorization =
sort . foldl (cartesianWith (*)) [1] . map (\(p, e) -> map (p^) [0..e])
Perl.
sub factors {
my %factorization = @_;
my @results = (1);
while (my ($p, $e) = each %factorization) {
@results = map {my $i = $_; map $i*$_, @results} map $p**$_, 0..$e;
}
sort {$a <=> $b} @results;
}
print join($,, factors(2, 3, 3, 1)), $/;
J.
/:~~.,*/"1/{:@({.^i.@{:@>:)"1 ] 2 3 ,: 3 1
1 2 3 4 6 8 12 24
这些都实现了同样的算法,即为每个因数对(p, e),生成列表p^0,p^1,...,p^e,并取所有这些列表中的笛卡尔积的乘积。