#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
#

func n_divisors(threshold, least_solution = Inf, k = 1, max_a = Inf, solutions = 1, n = 1) {

    if (solutions == threshold) {
        return n
    }

    if (solutions > threshold) {
        return least_solution
    }

    var p = k.prime

    for a in (1 .. max_a) {
        n *= p
        break if (n > least_solution)
        least_solution = __FUNC__(threshold, least_solution, k+1, a, solutions * (a + 1), n)
    }

    return least_solution
}

assert_eq(gather {
    say (take(n_divisors(15)))
    say (take(n_divisors(60)))
    say (take(n_divisors(1000)))
}, [144, 5040, 810810000])
