Skip to content

Instantly share code, notes, and snippets.

@rosslebeau
Created August 13, 2016 18:28
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 rosslebeau/2526c7ca040bd857a0a88ae2ca10154f to your computer and use it in GitHub Desktop.
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
// 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