diff --git a/cube_count.py b/cube_count.py new file mode 100644 index 0000000000..db07287845 --- /dev/null +++ b/cube_count.py @@ -0,0 +1,33 @@ +def int_cuberoot_floor(x): + """Return floor(cuberoot(x)) for nonnegative integer x using binary search.""" + if x < 0: + raise ValueError("x must be nonnegative") + lo, hi = 0, int(x**(1/3)) + 2 # initial bracket (safe) + # make hi definitely large enough + while hi**3 <= x: + hi *= 2 + while lo + 1 < hi: + mid = (lo + hi) // 2 + if mid**3 <= x: + lo = mid + else: + hi = mid + return lo + +def count_pairs(n): + """Return count of pairs (a>=1, b>=0) of integers with a^3 + b^3 = n, + and also return the list of such pairs.""" + pairs = [] + max_a = int_cuberoot_floor(n) # a^3 <= n + for a in range(1, max_a + 1): + rem = n - a**3 + if rem < 0: + break + b = int_cuberoot_floor(rem) + if b**3 == rem: + pairs.append((a, b)) + return len(pairs), pairs + +# Examples +print(count_pairs(9)) # -> (2, [(1,2),(2,1)]) +print(count_pairs(27)) # -> (1, [(3,0)])