How to resolve the algorithm Taxicab numbers step by step in the Python programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Taxicab numbers step by step in the Python programming language
Table of Contents
Problem Statement
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
Taxicab numbers are also known as:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Taxicab numbers step by step in the Python programming language
1. Identifying Cube Roots
cube2n = {x**3:x for x in range(1, 1201)}
sums2cubes = defaultdict(set)
cube2n
is a dictionary that maps cube values (from 1 to 1,200,000) to their corresponding roots (from 1 to 1200).sums2cubes
is a defaultdict that maps sums of two cubes to sets of tuples representing the cube roots that produce those sums.
2. Computing Sums of Two Cubes
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
product(cube2n, cube2n)
generates all possible pairs of cube values.- For each pair
(c1, c2)
wherec1 >= c2
, the sumc1 + c2
is calculated and used as a key in thesums2cubes
dictionary. - A tuple
(cube2n[c1], cube2n[c2])
is then added to the set associated with that key, representing the pair of cube roots that produce the given sum.
3. Identifying Taxicab Numbers
taxied = sorted((k, v) for k,v in sum2cubes.items() if len(v) >= 2)
sorted(...)
sorts thesum2cubes
dictionary based on the keys (sums of two cubes).- The
(k, v)
tuples represent pairs of sum and their associated set of tuples. - The
len(v) >= 2
filter ensures that only sums with multiple representations as sums of two cubes are considered.
4. Printing the First 25 and Last 6 Taxicab Numbers
#pp(len(taxied)) # 2068
for t in enumerate(taxied[:25], 1):
pp(t)
print('...')
for t in enumerate(taxied[2000-1:2000+6], 2000):
pp(t)
pp(len(taxied))
prints the total number of taxicab numbers found (2068).- The code then prints the first 25 and the last 6 taxicab numbers in a tuple format showing the sum and its representations as sums of two cubes.
5. Computing Taxicab Numbers with Cube Roots
cubes, crev = [x**3 for x in range(1,1200)], {}
# for cube root lookup
for x,x3 in enumerate(cubes): crev[x3] = x + 1
sums = sorted(x+y for x in cubes for y in cubes if y < x)
idx = 0
for i in range(1, len(sums)-1):
if sums[i-1] != sums[i] and sums[i] == sums[i+1]:
idx += 1
if idx > 25 and idx < 2000 or idx > 2006: continue
n,p = sums[i],[]
for x in cubes:
if n-x < x: break
if n-x in crev:
p.append((crev[x], crev[n-x]))
print "%4d: %10d"%(idx,n),
for x in p: print " = %4d^3 + %4d^3"%x,
print
- This section uses a more efficient way to compute taxicab numbers by leveraging precomputed cube values and cube root lookups.
- It prints the first 25 and the last 6 taxicab numbers in a different representation, where the sum is followed by a list of tuples representing the cube roots that produce that sum.
6. Generating Taxicab Numbers with a Priority Queue
from heapq import heappush, heappop
def cubesum():
h,n = [],1
while True:
while not h or h[0][0] > n**3: # could also pre-calculate cubes
heappush(h, (n**3 + 1, n, 1))
n += 1
(s, x, y) = heappop(h)
yield((s, x, y))
y += 1
if y < x: # should be y <= x?
heappush(h, (x**3 + y**3, x, y))
def taxis():
out = [(0,0,0)]
for s in cubesum():
if s[0] == out[-1][0]:
out.append(s)
else:
if len(out) > 1: yield(out)
out = [s]
- This section demonstrates a different way of generating taxicab numbers using a priority queue (
heapq
). - The
cubesum()
generator yields tuples representing sums of two cubes, starting with the smallest possible sum (1^3 + 1^3). - The
taxis()
function then groups these sums into taxicab numbers and yields them as lists of tuples.
7. Printing the First 2006 Taxicab Numbers
n = 0
for x in taxis():
n += 1
if n >= 2006: break
if n <= 25 or n >= 2000:
print(n, x)
- The code iterates over the taxicab numbers generated by
taxis()
, printing the first 2006 numbers. - It filters out numbers that are already printed in the previous section (those in the first 25 or last 6 positions).
Source code in the python programming language
from collections import defaultdict
from itertools import product
from pprint import pprint as pp
cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
taxied = sorted((k, v) for k,v in sum2cubes.items() if len(v) >= 2)
#pp(len(taxied)) # 2068
for t in enumerate(taxied[:25], 1):
pp(t)
print('...')
for t in enumerate(taxied[2000-1:2000+6], 2000):
pp(t)
cubes, crev = [x**3 for x in range(1,1200)], {}
# for cube root lookup
for x,x3 in enumerate(cubes): crev[x3] = x + 1
sums = sorted(x+y for x in cubes for y in cubes if y < x)
idx = 0
for i in range(1, len(sums)-1):
if sums[i-1] != sums[i] and sums[i] == sums[i+1]:
idx += 1
if idx > 25 and idx < 2000 or idx > 2006: continue
n,p = sums[i],[]
for x in cubes:
if n-x < x: break
if n-x in crev:
p.append((crev[x], crev[n-x]))
print "%4d: %10d"%(idx,n),
for x in p: print " = %4d^3 + %4d^3"%x,
print
from heapq import heappush, heappop
def cubesum():
h,n = [],1
while True:
while not h or h[0][0] > n**3: # could also pre-calculate cubes
heappush(h, (n**3 + 1, n, 1))
n += 1
(s, x, y) = heappop(h)
yield((s, x, y))
y += 1
if y < x: # should be y <= x?
heappush(h, (x**3 + y**3, x, y))
def taxis():
out = [(0,0,0)]
for s in cubesum():
if s[0] == out[-1][0]:
out.append(s)
else:
if len(out) > 1: yield(out)
out = [s]
n = 0
for x in taxis():
n += 1
if n >= 2006: break
if n <= 25 or n >= 2000:
print(n, x)
You may also check:How to resolve the algorithm Regular expressions step by step in the Swift programming language
You may also check:How to resolve the algorithm Jensen's Device step by step in the Sidef programming language
You may also check:How to resolve the algorithm Bin given limits step by step in the Raku programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the Logtalk programming language
You may also check:How to resolve the algorithm Abelian sandpile model step by step in the Perl programming language