I would like to find the highest value m = a*b that satisfies some condition C(m), where
1 <= a <= b <= 1,000,000.
In order to do that, I'd like to iterate all pairs of a,b in decreasing order of a*b.
For example, for values up to 5, the order would be:
5 x 5 = 25
4 x 5 = 20
4 x 4 = 16
3 x 5 = 15
3 x 4 = 12
2 x 5 = 10
3 x 3 = 9
2 x 4 = 8
2 x 3 = 6
1 x 5 = 5
1 x 4 = 4
2 x 2 = 4
1 x 3 = 3
1 x 2 = 2
1 x 1 = 1
So far I've come up with a BFS-like tree search, where I generate candidates from the current "visited" set and pick the highest value candidate, but it's a tangled mess, and I'm not sure about correctness. I wonder if there's some sort of trick I'm missing.
I'm also interested in the more general case of ordering by any monotonic function f(a,b), if such a thing exists.
For illustration, C(m) could be "return true if m2+m+41 is prime, otherwise return false", but I'm really looking for a general approach.