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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Increasing gaps between consecutive Niven numbers step by step in the Nim 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 Nim programming language

Source code in the nim programming language

import strformat

func digitsSum(n, sum: uint64): uint64 =
  ## Returns the sum of the digits of n given the sum of the digits of n - 1.
  result = sum + 1
  var n = n
  while n > 0 and n mod 10 == 0:
    dec result, 9
    n = n div 10

func divisible(n, d: uint64): bool {.inline.} =
  if (d and 1) == 0 and (n and 1) == 1:
    return false
  result = n mod d == 0

when isMainModule:

  echo "Gap index  Gap  Niven index  Niven number"

  var
    niven, gap, sum, nivenIndex = 0u64
    previous, gapIndex = 1u64

  while gapIndex <= 32:
    inc niven
    sum = digitsSum(niven, sum)
    if divisible(niven, sum):
      if niven > previous + gap:
        gap = niven - previous
        echo fmt"{gapIndex:9d} {gap:4d} {nivenIndex:12d} {previous:13d}"
        inc gapIndex
      previous = niven
      inc nivenIndex


  

You may also check:How to resolve the algorithm Unicode variable names step by step in the BaCon programming language
You may also check:How to resolve the algorithm Strip control codes and extended characters from a string step by step in the Go programming language
You may also check:How to resolve the algorithm The sieve of Sundaram step by step in the Amazing Hopper programming language
You may also check:How to resolve the algorithm Self-describing numbers step by step in the CLU programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the BQN programming language