Proper divisors: Difference between revisions

jq
(jq)
Line 118:
10: [1, 2, 5]
15120: 79</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
In the following, proper_divisors returns a stream. In order to count the number of items in the stream economically, we first define "count(stream)":
<lang jq>def count(stream): reduce stream as $i (0; . + 1);
 
def proper_divisors:
. as $n
| range(1; 1 + ($n / 2 | floor)) as $i
| if ($n % $i) == 0 then $i else empty end;
 
# The first integer in 1 .. n inclusive
# with the maximal number of proper divisors in that range:
def most_proper_divisors(n):
reduce range(1; n+1) as $i
( [];
count( $i | proper_divisors ) as $count
| if length == 0 or $count > .[1] then [$i, $count] else . end);</lang>
'''The tasks:'''
<lang jq>"The proper divisors of the numbers 1 to 10 inclusive are:",
(range(1;11) as $i | "\($i): \( [ $i | proper_divisors] )"),
"",
"The pair consisting of the least number in the range 1 to 20,000 with",
"the maximal number proper divisors together with the corresponding",
"count of proper divisors is:",
most_proper_divisors(20000) </lang>
{{out}}
<lang sh>$ jq -n -c -r -f /Users/peter/jq/proper_divisors.jq
The proper divisors of the numbers 1 to 10 inclusive are:
1: []
2: [1]
3: [1]
4: [1,2]
5: [1]
6: [1,2,3]
7: [1]
8: [1,2,4]
9: [1,3]
10: [1,2,5]
 
The pair consisting of the least number in the range 1 to 20,000 with
the maximal number proper divisors together with the corresponding
count of proper divisors is:
[15120,79]</lang>
 
=={{header|Perl}}==
2,489

edits