Added correct implementation.

master
Tomasz Polgrabia 2025-01-06 22:01:51 +01:00
parent 1d997a3ece
commit 4ec716caa4
2 changed files with 45 additions and 3 deletions

View File

@ -1,5 +1,4 @@
# Solution for 17.9
This solution uses Eratosthenes method which is simple but space O(n) which is
less than ideal. Maybe there are better solutions because it requires also to give
the max size of that array which is less than desirable.
- Program.kt is not correct (didn't calculate what it was needed)
- Program2.kt is correct

View File

@ -0,0 +1,43 @@
package pl.polgrabia.demos.crackingcodeinterview.t17x9
import java.util.PriorityQueue
import kotlin.system.exitProcess
fun main() {
print("Give k number (>= 1): ")
val kNumber = readln().toInt()
if (kNumber < 1) {
System.err.println("kNumber cannot be smaller than as it's first number of 3,5,7")
exitProcess(1)
}
val q = PriorityQueue<PrimeMultiple>(
100
) { o1, o2 ->
o1.multipleNr - o2.multipleNr
}
q.add(PrimeMultiple(1))
var kGenerated = 0
var lastProcessed : Int = -1
while(kGenerated < kNumber) {
val el = q.remove()
if (el.multipleNr <= lastProcessed) {
continue
}
lastProcessed = el.multipleNr
println("${++kGenerated} multiple is ${el.multipleNr}")
q.add(PrimeMultiple(el.multipleNr*3))
q.add(PrimeMultiple(el.multipleNr*5))
q.add(PrimeMultiple(el.multipleNr*7))
}
// println("K$kNumber multiple for 3,5,7 is: $lastProcessed")
}
data class PrimeMultiple(
var multipleNr: Int
)