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
Here's a not particularly efficient way to do this with a heap in Python. This is probably the same thing as the BFS you mentioned, but it's fairly clean. (If someone comes up with a direct algorithm, that would of course be better.)
import heapq # <-this module's API is gross. why no PriorityQueue class?
def pairs_by_reverse_prod(n):
# put n things in heap, since of course i*j > i*(j-1); only do i <= j
# first entry is negative of product, since this is a min heap
to_do = [(-i * n, i, n) for i in xrange(1, n+1)]
heapq.heapify(to_do)
while to_do:
# first elt of heap has the highest product
_, i, j = to_do[0]
yield i, j
# remove it from the heap, replacing if we want to replace
if j > i:
heapq.heapreplace(to_do, (-i * (j-1), i, j-1))
else:
heapq.heappop(to_do)