# Almost prime

Efficient algorithm for generating all the `k`-almost prime numbers in a given range `[a,b]`:

```ruby
func almost_primes(a, b, k) {

    a = max(2**k, a)
    var arr = []

    func (m, lo, k) {

        var hi = idiv(b,m).iroot(k)

        if (k == 1) {

            lo = max(lo, idiv_ceil(a, m))

            each_prime(lo, hi, {|p|
                arr << m*p
            })

            return nil
        }

        each_prime(lo, hi, {|p|

            var t = m*p
            var u = idiv_ceil(a, t)
            var v = idiv(b, t)

            next if (u > v)

            __FUNC__(t, p, k-1)
        })
    }(1, 2, k)

    return arr.sort
}

for k in (1..5) {
    var (x=10, lo=1, hi=2)
    var arr = []
    loop {
        arr += almost_primes(lo, hi, k)
        break if (arr.len >= x)
        lo = hi+1
        hi = 2*lo
    }
    say arr.first(x)
}
```

#### Output:

```
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
[4, 6, 9, 10, 14, 15, 21, 22, 25, 26]
[8, 12, 18, 20, 27, 28, 30, 42, 44, 45]
[16, 24, 36, 40, 54, 56, 60, 81, 84, 88]
[32, 48, 72, 80, 108, 112, 120, 162, 168, 176]
```

Also built-in:

```ruby
for k in (1..5) {
    var x = 10
    say k.almost_primes(x.nth_almost_prime(k))
}
```

(same output as above)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://trizen.gitbook.io/sidef-lang/programming_tasks/a/almost_prime.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
