백준 - 4948 베르트랑 공준
문제
4948 베르트랑 공준
답
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
fun main() {
val inputs = readInputs()
val isPrimeNumbers = getIsPrimeNumbers(inputs.maxOf { it } * 2)
printOutput(inputs, isPrimeNumbers)
}
fun printOutput(inputs: MutableList<Int>, primeNumbers: BooleanArray) = inputs.forEach { println((it + 1..it * 2).count { x -> primeNumbers[x] }) }
fun getIsPrimeNumbers(to: Int): BooleanArray {
val isPrimeNumbers = BooleanArray(to + 1) { true }
isPrimeNumbers[0] = false
isPrimeNumbers[1] = false
val max = kotlin.math.sqrt(isPrimeNumbers.size.toDouble()).toInt()
for(index in (2..max)) {
if(!isPrimeNumbers[index]) continue
for(i in ((index * index)until isPrimeNumbers.size) step index) {
isPrimeNumbers[i] = false
}
}
return isPrimeNumbers
}
fun readInputs(): MutableList<Int> {
val inputs = mutableListOf<Int>()
while (true) {
val input = readln().trim()
if(input == "") continue
if(input == "0") return inputs
inputs.add(input.toInt())
}
}
Reference
소수 (수론)
에라토스테네스의 체
This post is licensed under CC BY 4.0 by the author.