-
-
Save dbatis/4edd792a049985d57d7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'dbatis' | |
def hardyRamanujan(upperLimit): | |
""" | |
Computes all cases of x^3 + y^3 = z^3 + g^3, where x <> y <> z <> g and x, y, z, g < upperLimit. | |
Example output: | |
>>> hardyRamanujan(20) | |
[[(1, 12, 1729), (9, 10, 1729)], [(2, 16, 4104), (9, 15, 4104)]] | |
Each item in the list is a collection of (x, y, x^3 + y^3) tuples which all match the same | |
sum. | |
""" | |
# compute all possible sums where x != y, complexity O(n^2) | |
sums = [(x, y, x**3 + y**3) for x in range(1, upperLimit) for y in range(x+1, upperLimit)] | |
# sort it by resulting sum, complexity O(n * log(n)) | |
sums.sort(key=lambda x: x[2]) | |
results = [] | |
# iterate once on sorted list, complexity O(n) | |
cmpVal = (0, 0, 0) | |
resultValue = [cmpVal] | |
for examinedVal in sums: | |
if cmpVal[2] != examinedVal[2]: # move on to next sum result | |
cmpVal = examinedVal | |
if len(resultValue) > 1: # do we have previous matches to append to results? | |
results.append(resultValue) | |
resultValue = [cmpVal] | |
else: | |
resultValue.append(examinedVal) | |
return results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment