How to resolve the algorithm Ascending primes step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Ascending primes step by step in the jq programming language

Table of Contents

Problem Statement

Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly is at least mildly interesting. Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is at least one significantly better and much faster way, needing a mere 511 odd/prime tests.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Ascending primes step by step in the jq programming language

Source code in the jq programming language

# Output: the stream of ascending primes, in order
def ascendingPrimes:
  # Generate the stream of primes beginning with the digit .
  # and with strictly ascending digits, without regard to order
  def generate:
    # strings
    def g:
      . as $first
      | tonumber as $n
      | select($n <= 9)
      | $first,
        ((range($n + 1;10) | tostring | g) as $x
         | $first + $x );
    tostring | g | tonumber | select(is_prime);

  [range(1;10) | generate] | sort[];

def task:
  def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
  [ascendingPrimes]
  | "There are \(length) ascending primes, namely:",
    ( _nwise(10) | map(lpad(10)) | join(" ") );

task

  

You may also check:How to resolve the algorithm URL encoding step by step in the jq programming language
You may also check:How to resolve the algorithm Empty program step by step in the ERRE programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Cobra programming language
You may also check:How to resolve the algorithm Towers of Hanoi step by step in the Ioke programming language
You may also check:How to resolve the algorithm String prepend step by step in the EasyLang programming language