Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NicholasTD07/12560358509df478cdc8b16cb734a328 to your computer and use it in GitHub Desktop.
Save NicholasTD07/12560358509df478cdc8b16cb734a328 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