-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path204.Count Primes.swift
46 lines (44 loc) · 1.02 KB
/
204.Count Primes.swift
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
func countPrimes(_ n: Int) -> Int {
if n == 0 || n == 1 {
return 0;
}
var count = 0;
var notPrime = [Bool].init(repeating:false,count:n);
for i in 2..<n {
if notPrime[i] == false {
count += 1;
var j = 2;
while i*j < n {
notPrime[i*j] = true;
j += 1;
}
}
}
return count;
}
func countPrimes2(_ n: Int) -> Int {
if n == 0 || n == 1 {
return 0;
}
var count = 0;
for i in 2..<n {
if isPrimeNum(i) {
count += 1;
}
}
return count;
}
func isPrimeNum(_ n:Int) -> Bool {
if n == 2 || n == 3 {
return true;
}
let count = Int(sqrt(Double(n)));
for i in 2...count {
if n%i == 0 {
return false;
}
}
return true;
}
}