-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSolution.kt
42 lines (38 loc) · 878 Bytes
/
Solution.kt
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
/**
* Created by Inno Fang on 2018/2/16.
*/
/**
* 20 / 20 test cases passed.
* Status: Accepted
* Runtime: 441 ms
*/
class Solution {
fun countPrimes(n: Int): Int {
var count = 0
val isPrime = BooleanArray(n) { true }
(2 until n).forEach { i ->
if (isPrime[i]) {
count++
(i until n step i).forEach { isPrime[it] = false }
}
}
return count
}
}
/**
* 20 / 20 test cases passed.
* Status: Accepted
* Runtime: 385 ms
*/
class Solution2 {
fun countPrimes(n: Int): Int {
val isPrime = BooleanArray(n) { true }
return (2 until n).count { i ->
if (isPrime[i]) (2 * i until n step i).forEach { isPrime[it] = false }
isPrime[i]
}
}
}
fun main(args: Array<String>) {
Solution2().countPrimes(10).let(::println)
}