-
-
Save NicholasTD07/12560358509df478cdc8b16cb734a328 to your computer and use it in GitHub Desktop.
Swift Prime Number Generator
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
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