How to find all taxicab numbers less than N?

前端 未结 8 1534
攒了一身酷
攒了一身酷 2021-01-30 14:11

A taxicab number is an integer that can be expressed as the sum of two cubes of integers in two different ways: a^3+b^3 = c^3+d^3. Design an algorithm to find all t

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 14:49

    I found the solution/code here : Time complexity O(N^2 logN), space complexity O(N) The solution is implemented by help of priority queues.

    Reverse thinking can be easily done by looking at the code. It can be done in an array of size N because the min sums are deleted from the array after comparing to the next minimum and then the array is made to size N by adding a new sum - (i^3 + (j+1)^3).

    A intuitive proof is here :

    Initially, we have added (1,1),(2,2),(3,3),...,(N,N) in the min-priority queue.

    Suppose a^+b^3=c^3+d^3, and (a,b) is the minimum that will be taken out of the priority queue next. To be able to detect this taxicab number, (c,d) must also be in the priority queue which would be taken out after (a,b).

    Note: We would be adding (a,b+1) after extracting (a,b) so there is no way that extraction of (a,b) would result in addition of (c,d) to the priority queue, so it must already exist in the priority queue.

    Now lets assume that (c,d) is not in the priority queue, because we haven't gotten to it yet. Instead, there is some (c,d−k) in the priority queue where k>0.

    Since (a,b) is being taken out, a^3+b^3≤c^3+(d−k)^3

    However, a^3+b^3=c^3+d^3

    Therefore,

    c^3+d^3≤c^3+(d−k)^3 d≤d−k k≤0

    Since k>0, this is impossible. Thus our assumption can never come to pass. Thus for every (a,b) which is being removed from the min-PQ, (c,d) is already in the min-PQ (or was just removed) if a^3+b^3=c^3+d^3

提交回复
热议问题