Enumerate grid points on 2D plane with descending order of (x * y)

前端 未结 8 1272
轻奢々
轻奢々 2021-02-09 11:55

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

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-09 12:01

    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.

提交回复
热议问题