forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountPrimes.swift
More file actions
32 lines (27 loc) · 801 Bytes
/
CountPrimes.swift
File metadata and controls
32 lines (27 loc) · 801 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Question Link: https://leetcode.com/problems/count-primes/
* Primary idea: Create a boolean array to determine prime or not,
* filter numbers are times of previous ones
*
* Time Complexity: O(n), Space Complexity: O(n)
*/
class CountPrimes {
func countPrimes(_ n: Int) -> Int {
guard n > 2 else {
return 0
}
var isPrime = [Bool](repeating: true, count: n)
for i in 2..<n {
if isPrime[i] {
for j in stride(from: 2 * i, to: n, by: i) {
isPrime[j] = false
}
}
}
var count = 1
for i in stride(from: 3, to: n, by: 2) {
count += isPrime[i] ? 1 : 0
}
return count
}
}