Skip to content

Instantly share code, notes, and snippets.

@lvalenta
Last active March 9, 2023 15:14
Show Gist options
  • Save lvalenta/07770221e7d653f6cfad6f2bda63af73 to your computer and use it in GitHub Desktop.
Save lvalenta/07770221e7d653f6cfad6f2bda63af73 to your computer and use it in GitHub Desktop.
import Foundation
func countPrimes(_ n: Int) -> Int {
var isPrime = [Bool](repeating: false, count: n+1)
var primeCount = 0
if n <= 1 {
return 0
}
var num = 2
let max = Int(sqrt(Double(n)))
while num <= max {
if !isPrime[num] {
var primeNum = num * num
while primeNum < n {
isPrime[primeNum] = true
primeNum += num
}
}
num += 1
}
num = 2
while num < n {
if !isPrime[num] {
primeCount += 1
}
num += 1
}
return primeCount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment