Given N > 0
and M > 0
, I want to enumerate all (x, y) pairs such that 1 <= x <= N and 1 <= y <= M in descending order of (x * y).
An
A dummy approach that loops from NxM to 1 searching for pairs that when multiplied produce the current number:
#!/usr/bin/perl
my $n = 5;
my $m = 4;
for (my $p = $n * $m; $p > 0; $p--) {
my $min_x = int(($p + $m - 1) / $m);
for my $x ($min_x..$n) {
if ($p % $x == 0) {
my $y = $p / $x;
print("x: $x, y: $y, p: $p\n");
}
}
}
For N=M, complexity is O(N3) but memory usage is O(1).
Update: Note that the complexity is not as bad as it seems because the number of elements to generate is already N2. For comparison, the generate-all-the-pairs-and-sort approach is O(N2logN) with O(N2) memory usage.