How to resolve the algorithm Harshad or Niven series step by step in the Cowgol programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Harshad or Niven series step by step in the Cowgol programming language

Table of Contents

Problem Statement

The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order.

The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:

Show your output here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Harshad or Niven series step by step in the Cowgol programming language

Source code in the cowgol programming language

include "cowgol.coh";

sub digitsum(n: uint16): (sum: uint8) is    
    sum := 0;
    while n != 0 loop
        sum := sum + (n % 10) as uint8;
        n := n / 10;
    end loop;
end sub;

sub nextHarshad(m: uint16): (n: uint16) is
    n := m;
    loop
        n := n + 1;
        if n % digitsum(n) as uint16 == 0 then
            return;
        end if;
    end loop;
end sub;

var n: uint16 := 0;
var i: uint16 := 0;

while n <= 1000 loop
    n := nextHarshad(n);
    i := i + 1;
    if i <= 20 then
        print_i16(n);
        print(" ");
    end if;
end loop;

print_nl();
print_i16(n);
print_nl();

  

You may also check:How to resolve the algorithm Identity matrix step by step in the D programming language
You may also check:How to resolve the algorithm Filter step by step in the REXX programming language
You may also check:How to resolve the algorithm Bitmap/Midpoint circle algorithm step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Largest proper divisor of n step by step in the Draco programming language
You may also check:How to resolve the algorithm Spiral matrix step by step in the J programming language