Product of min and max prime factors: Difference between revisions

(Added Go)
Line 243:
9 82 6889 14 85 86 87 22 7921 10
91 46 93 94 95 6 9409 14 33 10</syntaxhighlight>
 
=={{header|jq}}==
# {{Works with jq}}
 
The following program will also work with gojq if the def of `_nwise/2`
is uncommented.
<syntaxhighlight lang=jq>
# Uncomment for gojq
# def _nwise($n):
# def nw: if length <= $n then . else .[0:$n] , (.[$n:] | nw) end;
# nw;
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
# Input: an integer
def isPrime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
else 5
| until( . <= 0;
if .*. > $n then -1
elif ($n % . == 0) then 0
else . + 2
| if ($n % . == 0) then 0
else . + 4
end
end)
| . == -1
end;
 
# Input: an integer
# Output: a stream of the prime divisors of the input, in order
def prime_divisors:
. as $n
| if . < 2 then empty
elif . == 2 then 2
else (select(. % 2 == 0) | 2),
(range(3; ($n / 2) + 1; 2) | select( ($n % . == 0) and isPrime)),
($n | select(isPrime))
end;
 
def greatest_prime_divisor:
def odd: if . % 2 == 1 then . else . + 1 end;
. as $n
| if . < 2 then empty
elif . == 2 then 2
else first(
($n | select(isPrime)),
((( (($n|odd) - 1) / 2) | odd) as $odd
| range( $odd; 2; -2) | select( ($n % . == 0) and isPrime)),
(select(. % 2 == 0) | 2) )
end;
 
# Output: a stream of the products
def productMinMaxPrimeFactors:
1,
(range(2; infinite)
| [ first(prime_divisors), greatest_prime_divisor] | .[0] * .[-1]);
 
"Product of the smallest and greatest prime factors of n for 1 to 100:",
([limit(100; productMinMaxPrimeFactors)]
| _nwise(10) | map(lpad(4)) | join(" "))
</syntaxhighlight>
 
'''Invocation'''
jq -nr -f product-of-min-and-max-prime-factors.jq
 
{{output}}
<pre>
Product of the smallest and greatest prime factors of n for 1 to 100:
1 4 9 4 25 6 49 4 9 10
121 6 169 14 15 4 289 6 361 10
21 22 529 6 25 26 9 14 841 10
961 4 33 34 35 6 1369 38 39 10
1681 14 1849 22 15 46 2209 6 49 10
51 26 2809 6 55 14 57 58 3481 10
3721 62 21 4 65 22 4489 34 69 14
5041 6 5329 74 15 38 77 26 6241 10
9 82 6889 14 85 86 87 22 7921 10
91 46 93 94 95 6 9409 14 33 10
</pre>
 
=={{header|Julia}}==
2,465

edits