> For the complete documentation index, see [llms.txt](https://trizen.gitbook.io/sidef-lang/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://trizen.gitbook.io/sidef-lang/programming_tasks/p/practical_numbers.md).

# Practical numbers

Built-in:

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

Slow implementation (as the task requires):

```ruby
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:

```ruby
func is_practical(n) {

    n.is_odd && return (n == 1)
    n.is_pos || return false

    var p = 1
    var f = n.factor_exp

    f.each_cons(2, {|a,b|
        p *= sigma(a.head**a.tail)
        b.head > (1 + p) && return false
    })

    return true
}
```

## Output:

```
There are 77 practical numbers in the range 1..333.
1, 2, 4, 6, 8, 12, 16, 18, 20, 24 ... 288, 294, 300, 304, 306, 308, 312, 320, 324, 330

  666 is practical? true
 6666 is practical? true
66666 is practical? false
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://trizen.gitbook.io/sidef-lang/programming_tasks/p/practical_numbers.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
