September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -0,0 +1,9 @@
|
|||
# Recent versions of jq include the following definition:
|
||||
# until/2 loops until cond is satisfied,
|
||||
# and emits the value satisfying the condition:
|
||||
def until(cond; next):
|
||||
def _until:
|
||||
if cond then . else (next|_until) end;
|
||||
_until;
|
||||
|
||||
def count(cond): reduce .[] as $x (0; if $x|cond then .+1 else . end);
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
# Is the input integer a prime?
|
||||
# "previous" must be the array of sorted primes greater than 1 up to (.|sqrt)
|
||||
def is_prime(previous):
|
||||
. as $in
|
||||
| (previous|length) as $plength
|
||||
| [false, 0] # state: [found, ix]
|
||||
| until( .[0] or .[1] >= $plength;
|
||||
[ ($in % previous[.[1]]) == 0, .[1] + 1] )
|
||||
| .[0] | not ;
|
||||
|
||||
# extend_primes expects its input to be an array consisting of
|
||||
# previously found primes, in order, and extends that array:
|
||||
def extend_primes:
|
||||
if . == null or length == 0 then [2]
|
||||
else . as $previous
|
||||
| if . == [2] then [2,3]
|
||||
else . + [(2 + .[length-1]) | until( is_prime($previous) ; . + 2)]
|
||||
end
|
||||
end;
|
||||
|
||||
# If . is an integer > 0 then produce an array of . primes;
|
||||
# otherwise emit an unbounded stream of primes:
|
||||
def primes:
|
||||
. as $n
|
||||
| if type == "number" and $n > 0 then
|
||||
null | until( length == $n; extend_primes )
|
||||
else [2] | recurse(extend_primes) | .[length - 1]
|
||||
end;
|
||||
|
||||
# Primes up to and possibly including n:
|
||||
def primes_upto(n):
|
||||
until( .[length-1] > n; extend_primes )
|
||||
| if .[length-1] > n then .[0:length-1] else . end;
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
"First 20 primes:", (20 | primes), "",
|
||||
|
||||
"Primes between 100 and 150:",
|
||||
(primes_upto(150) | map(select( 100 < .))), "",
|
||||
|
||||
"The 10,000th prime is \( 10000 | primes | .[length - 1] )", "",
|
||||
|
||||
(( primes_upto(8000) | count( . > 7700) | length) as $length
|
||||
| "There are \($length) primes twixt 7700 and 8000.")
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
$ jq -r -c -n -f Extensible_prime_generator.jq
|
||||
First 20 primes:
|
||||
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71]
|
||||
|
||||
Primes between 100 and 150:
|
||||
[101,103,107,109,113,127,131,137,139,149]
|
||||
|
||||
The 10,000th prime is 104729
|
||||
|
||||
There are 30 primes twixt 7700 and 8000.
|
||||
Loading…
Add table
Add a link
Reference in a new issue