Skip to content

Instantly share code, notes, and snippets.

@GINK03
Created July 22, 2018 16:05
Show Gist options
  • Save GINK03/9bc4d9fb58f90cbb7e887280adcd6b52 to your computer and use it in GitHub Desktop.
Save GINK03/9bc4d9fb58f90cbb7e887280adcd6b52 to your computer and use it in GitHub Desktop.
almost prime
fun Int.k_prime(x: Int): Boolean {
    var n = x
    var f = 0
    var p = 2
    while (f < this && p * p <= n) {
        while (0 == n % p) { n /= p; f++ }
        p++
    }
    return f + (if (n > 1) 1 else 0) == this
}
 
fun Int.primes(n : Int) : List<Int> {
    var i = 2
    var list = mutableListOf<Int>()
    while (list.size < n) {
        if (k_prime(i)) list.add(i)
        i++
    }
    return list
}
 
fun main(args: Array<String>) {
    for (k in 1..5)
        println("k = $k: " + k.primes(10))
}
k = 1: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
k = 2: [4, 6, 9, 10, 14, 15, 21, 22, 25, 26]
k = 3: [8, 12, 18, 20, 27, 28, 30, 42, 44, 45]
k = 4: [16, 24, 36, 40, 54, 56, 60, 81, 84, 88]
k = 5: [32, 48, 72, 80, 108, 112, 120, 162, 168, 176]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment