Practical numbers

Built-in:

say is_practical(2**128 + 1)   #=> false
say is_practical(2**128 + 4)   #=> true

Slow implementation (as the task requires):

func is_practical(n) {

    var set = Set()

    n.divisors.grep { _ < n }.subsets {|*a|
        set << a.sum
    }

    1..n-1 -> all { set.has(_) }
}

var from = 1
var upto = 333

var list = (from..upto).grep { is_practical(_) }

say "There are #{list.len} practical numbers in the range #{from}..#{upto}."
say "#{list.first(10).join(', ')} ... #{list.last(10).join(', ')}\n"

for n in ([666, 6666, 66666]) {
    say "#{'%5s' % n } is practical? #{is_practical(n)}"
}

Efficient algorithm:

Output:

Last updated

Was this helpful?