Created
August 13, 2016 18:28
-
-
Save rosslebeau/2526c7ca040bd857a0a88ae2ca10154f to your computer and use it in GitHub Desktop.
Generate all Ramanujan numbers: (a^3) + (b^3) = (c^3) + (d^3), where 0 < a, b, c, d < n
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
// Generate all Ramanujan numbers: (a^3) + (b^3) = (c^3) + (d^3) | |
// Where 0 < a, b, c, d < n | |
let n = 1000 | |
let cubes = (0..<n).map({$0*$0*$0}) | |
let cubeCount = cubes.count | |
var sumsOfPairs = [Int: (Int, Int)]() | |
var ramanujans = [Int: [(Int, Int)]]() | |
(1..<(cubeCount - 1)).forEach({a in | |
((a + 1)..<cubeCount).forEach({b in | |
let (a3, b3) = (cubes[a], cubes[b]) | |
let sum = a3 + b3 | |
if let (c, d) = sumsOfPairs[sum] { | |
if var r = ramanujans[sum] { | |
r.append((a, b)) | |
} else { | |
ramanujans[sum] = [(a, b), (c, d)] | |
} | |
} else { | |
sumsOfPairs[sum] = (a, b) | |
} | |
}) | |
}) | |
let sortedRamanujans = ramanujans.sorted(isOrderedBefore: {$0.0 < $1.0}) | |
for (ramanujanNumber, cubePairs) in sortedRamanujans { | |
print("Ramanujan Number: \(ramanujanNumber), cube pairs: \(cubePairs)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment