Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions cube_count.py
Original file line number Diff line number Diff line change
@@ -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)])