How to resolve the algorithm Smith numbers step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Smith numbers step by step in the jq programming language

Table of Contents

Problem Statement

Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers.

Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number.

Write a program to find all Smith numbers below 10000.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Smith numbers step by step in the jq programming language

Source code in the jq programming language

def is_prime:
  . as $n
  | if ($n < 2)         then false
    elif ($n % 2 == 0)  then $n == 2
    elif ($n % 3 == 0)  then $n == 3
    elif ($n % 5 == 0)  then $n == 5
    elif ($n % 7 == 0)  then $n == 7
    elif ($n % 11 == 0) then $n == 11
    elif ($n % 13 == 0) then $n == 13
    elif ($n % 17 == 0) then $n == 17
    elif ($n % 19 == 0) then $n == 19
    else {i:23}
         | until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
	 | .i * .i > $n
    end;

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

# emit a stream of the prime factors as per prime factorization
def prime_factors:
  . as $num
  | def m($p):  # emit $p with appropriate multiplicity
      $num | while( . % $p == 0; . / $p )
      | $p ;
  if (. % 2) == 0 then m(2) else empty end,
  (range(3; 1 + (./2); 2) 
    | select(($num % .) == 0 and is_prime)
    | m(.));

# input should be an integer
def is_smith:
  def sumdigits:
    tostring|explode|map([.]|implode|tonumber)| add;
  (is_prime|not) and
    (sumdigits == sum(prime_factors|sumdigits));

"Smith numbers up to 10000:\n",
(range(1; 10000) | select(is_smith))

  

You may also check:How to resolve the algorithm Numerical integration/Gauss-Legendre Quadrature step by step in the Julia programming language
You may also check:How to resolve the algorithm Greyscale bars/Display step by step in the C programming language
You may also check:How to resolve the algorithm Bitmap/Bresenham's line algorithm step by step in the Prolog programming language
You may also check:How to resolve the algorithm Grayscale image step by step in the Fortran programming language
You may also check:How to resolve the algorithm Animation step by step in the Go programming language