백준 - 2581 소수
문제
2581 소수
답
kotlin code
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
fun main() {
q2581()
}
fun q2581() {
val min = readln().toInt()
val max = readln().toInt()
val result = (min..max).filter { isPrime(it) }
if(result.isEmpty())
println(-1)
else {
println(result.sum())
println(result.minOf { it })
}
}
private fun isPrime(n: Int): Boolean = when {
n == 2 -> true
n < 2 || n.isOdd() -> false
else -> {
var result = true
for (i in 3..n/2) {
if (n % i == 0) {
result = false
break
}
}
result
}
}
private fun Int.isOdd(): Boolean {
return this % 2 == 0
}
This post is licensed under CC BY 4.0 by the author.