Count all prime numbers

[Question] Count all prime numbers from given n
Example

// TC: O(loglog(n))
// SC: O(n)
class Solution {
    func countPrimes(_ n: Int) -> Int {
        
        guard n > 2 else { return 0 }
        
        var count = 0
        var isPrimeArray = Array(repeating: true, count: n)
        isPrimeArray[0] = false
        isPrimeArray[1] = false
        
        var current = 2
        
        // Sieve of Eratosthenes algorithm
        while current * current < n {
            if isPrimeArray[current] {
                var multiple = 2
                while current * multiple < n {
                    isPrimeArray[current * multiple] = false
                    multiple += 1
                }
            }
            current += 1
        }
        
        // Count the prime numbers
        for i in 2..<n {
            if isPrimeArray[i] {
                count += 1
            }
        }
        
        return count
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *