Skip to content

Instantly share code, notes, and snippets.

@halbkreativ
Created December 5, 2015 03:04
Show Gist options
  • Save halbkreativ/c83189e223d20389455d to your computer and use it in GitHub Desktop.
Save halbkreativ/c83189e223d20389455d to your computer and use it in GitHub Desktop.
Primes in Apple's Swift
import Cocoa
import Foundation
func isPrime(n: Int) -> Bool {
if n < 2 {
return false // are not primes
}
let limit = Int(sqrt(Float(n)))
if limit < 2 {
return true // 2, 3 are primes
}
for i in 2...limit {
if n % i == 0 {
return false
}
}
return true
}
var primes: [Int] = []
for i in 2...100 {
if isPrime(i) {
primes.append(i)
}
}
print(primes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment