Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Last active May 22, 2022 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/ebc448a81317b0d3c9a9cd64ef06537e to your computer and use it in GitHub Desktop.
Save saxbophone/ebc448a81317b0d3c9a9cd64ef06537e to your computer and use it in GitHub Desktop.
Least common base function --will probably infinite-loop for inputs without an ideal answer
from itertools import combinations
from math import log, ceil
def common_bases(x: int, y: int) -> int:
"""
Returns a list of all the bases common to x and y
That is to say, all bases n such that n can be raised by an integer power to
produce x or y
The list returned is sorted in ascending order, and may be empty if there
are no common bases
"""
# try the nth root of x for n in {2..x-1}, and same for y
# keep any which are integers
x_roots = {round(x ** (1/xr)) for xr in range(2, x) if round(x ** (1/xr)) ** xr == x}
y_roots = {round(y ** (1/yr)) for yr in range(2, y) if round(y ** (1/yr)) ** yr == y}
# return the sorted intersection of the integer roots of x and y
return list(sorted(x_roots.intersection(y_roots)))
def lcb(x: int, y: int) -> int:
"""
Attempts to find the least common base to both x and y, that is to say,
a number (t) that can be raised by some powers a,b to make x,y respectively
"""
return common_bases(x, y)[:1]
def gcb(x: int, y: int) -> int:
"""
Attempts to find the greatest common base to both x and y, that is to say,
a number (t) that can be raised by some powers a,b to make x,y respectively
"""
return common_bases(x, y)[-1:]
# find all common base pairs up to 1000
print('x,y,lcb,gcb')
for x, y in combinations(range(1, 1001), 2):
l = lcb(x, y)
g = gcb(x, y)
if l and g:
print('{},{},{},{}'.format(x, y, l[0], g[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment