How to find all taxicab numbers less than N?

前端 未结 8 1514
攒了一身酷
攒了一身酷 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:50

    The time complexity of the algorithm can't be less than O(N2) in any case, since you might print up to O(N2) taxicab numbers.

    To reduce space usage you could, in theory, use the suggestion mentioned here: little link. Basically, the idea is that first you try all possible pairs a, b and find the solution to this:

    a = 1 − (p − 3 * q)(p2 + 3 * q2)

    b = −1 + (p + 3 * q)(p2 + 3q2)

    Then you can find the appropriate c, d pair using:

    c = (p + 3 * q) - (p2 + 3 * q2)

    d = -(p - 3 * q) + (p2 + 3 * q2)

    and check whether they are both less than N. The issue here is that solving that system of equations might get a bit messy (by 'a bit' I mean very tedious).

    The O(N2) space solution is much simpler, and it'd probably be efficient enough since anything of quadratic time complexity that can run in reasonable time limits will probably be fine with quadratic space usage.

    I hope that helped!

    0 讨论(0)
  • 2021-01-30 14:55
    1. create an array: 1^3, 2^3, 3^3, 4^3, ....... k^3. such that k^3 < N and (k+1)^3 > N. the array size would be ~ (N)^(1/3). the array is sorted order.
    2. use 2sum technique (link) in lineal time proportional to the array size. if we find 2 pairs of numbers, that is a hit.
    3. looping through step 2 by decreasing N by 1 each time.

    This will use O(N^(1/3)) extra space and ~ O(N^(4/3)) time.

    0 讨论(0)
提交回复
热议问题