How to resolve the algorithm Increasing gaps between consecutive Niven numbers step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Increasing gaps between consecutive Niven numbers step by step in the jq programming language

Table of Contents

Problem Statement

Note:   Niven   numbers are also called   Harshad   numbers.

Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Increasing gaps between consecutive Niven numbers step by step in the jq programming language

Source code in the jq programming language

def add(s): reduce s as $x (null; . + $x);

def digit_sum:
  def digits: tostring | explode[] | [.] | implode | tonumber;
  add(digits);

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

# input: the largest Niven number to be considered (null => infinite)
# output: a stream of informative JSON objects -
# {gap_index, gap, niven_index, previous}
def nivens:
  (. // infinite) as $limit
  | { gap: 0,
      gap_index: 1,
      niven: 1,
      niven_index: 1}
  | foreach range(2; $limit+1) as $n (.;
      .emit = false
      | if $n % ($n | digit_sum) == 0 
        then if $n > .niven + .gap
             then .gap = $n - .niven
	     | .emit = {gap_index, gap, niven_index, niven}
     	     | .gap_index += 1
	     else .
	     end
        | .niven = $n
        | .niven_index += 1
        else .
	end;
      select(.emit).emit );

"Gap index  Gap  Niven index  Niven number",
"---------  ---  -----------  ------------",
( 1E7 | nivens
  | "\(.gap_index|lpad(9)) \(.gap|lpad(4)) \(.niven_index|lpad(12)) \(.niven|lpad(13))" )

  

You may also check:How to resolve the algorithm Ordered words step by step in the SPL programming language
You may also check:How to resolve the algorithm String case step by step in the mIRC Scripting Language programming language
You may also check:How to resolve the algorithm Magnanimous numbers step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Nth root step by step in the C# programming language
You may also check:How to resolve the algorithm Sort a list of object identifiers step by step in the Elixir programming language