Practical numbers: Difference between revisions
Content added Content deleted
(Please keep your Haskell out of the Python section. (Or at least translate fully).) |
(Added Wren) |
||
Line 439: | Line 439: | ||
6666 is practical? True |
6666 is practical? True |
||
66666 is practical? False</pre> |
66666 is practical? False</pre> |
||
=={{header|Wren}}== |
|||
{{libheader|Wren-math}} |
|||
<lang ecmascript>import "/math" for Int, Nums |
|||
var powerset // recursive |
|||
powerset = Fn.new { |set| |
|||
if (set.count == 0) return [[]] |
|||
var head = set[0] |
|||
var tail = set[1..-1] |
|||
return powerset.call(tail) + powerset.call(tail).map { |s| [head] + s } |
|||
} |
|||
var isPractical = Fn.new { |n| |
|||
if (n == 1) return true |
|||
var divs = Int.properDivisors(n) |
|||
var subsets = powerset.call(divs) |
|||
var found = List.filled(n, false) |
|||
var count = 0 |
|||
for (subset in subsets) { |
|||
var sum = Nums.sum(subset) |
|||
if (sum > 0 && sum < n && !found[sum]) { |
|||
found[sum] = true |
|||
count = count + 1 |
|||
if (count == n - 1) return true |
|||
} |
|||
} |
|||
return false |
|||
} |
|||
System.print("In the range 1..333, there are:") |
|||
var count = 0 |
|||
var practical = [] |
|||
for (i in 1..333) { |
|||
if (isPractical.call(i)) { |
|||
count = count + 1 |
|||
practical.add(i) |
|||
} |
|||
} |
|||
System.print(" %(count) practical numbers") |
|||
System.print(" The first ten are %(practical[0..9])") |
|||
System.print(" The final ten are %(practical[-10..-1])") |
|||
System.print("\n666 is practical: %(isPractical.call(666))")</lang> |
|||
{{out}} |
|||
<pre> |
|||
In the range 1..333, there are: |
|||
77 practical numbers |
|||
The first ten are [1, 2, 4, 6, 8, 12, 16, 18, 20, 24] |
|||
The final ten are [288, 294, 300, 304, 306, 308, 312, 320, 324, 330] |
|||
666 is practical: true |
|||
</pre> |