Create a gist now

Instantly share code, notes, and snippets.

Generate all Ramanujan numbers: (a^3) + (b^3) = (c^3) + (d^3), where 0 < a, b, c, d < n
// 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