Skip to content

Instantly share code, notes, and snippets.

@sam-w
Created April 30, 2016 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sam-w/3a759c37d824034522ae1a59af6f9374 to your computer and use it in GitHub Desktop.
Save sam-w/3a759c37d824034522ae1a59af6f9374 to your computer and use it in GitHub Desktop.
Swift Prime Number Generator
static func getPrimes(to n: Int) -> [Int] {
let xmody = (1...n)
.map { x in (1...n).map { y in x % y } }
let primes = xmody
.map { mods in
mods.enumerate()
.filter { y, mod in mod == 0 }
.map { y, mod in y + 1 } // divisors for x
}
.enumerate()
.filter { x, zs in
guard let z0 = zs.first, z1 = zs.last where zs.count <= 2 else {
return false
}
return z0 == 1 && z1 == x + 1
}
.map { x, _ in x + 1 }
return primes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment