Order (a,b) pairs by result of a*b

前端 未结 4 2020
离开以前
离开以前 2021-01-18 18:59

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

4条回答
  •  失恋的感觉
    2021-01-18 19:36

    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)
    

提交回复
热议问题