Harshad or Niven series: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 221: Line 221:
#include <iostream>
#include <iostream>


int quersumme ( int number ) {
int sumDigits ( int number ) {
int sum = 0 ;
int sum = 0 ;
while ( number != 0 ) {
while ( number != 0 ) {
Line 231: Line 231:


bool isHarshad ( int number ) {
bool isHarshad ( int number ) {
return number % ( quersumme ( number ) ) == 0 ;
return number % ( sumDigits ( number ) ) == 0 ;
}
}



Revision as of 18:51, 2 March 2015

Task
Harshad or Niven series
You are encouraged to solve this task according to the task description, using any language you may know.

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 list the first twenty members of the sequence and list the first Harshad number greater than 1000.

Show your output here.

Ada

<lang Ada>with Ada.Text_IO;

procedure Harshad is

  function Next(N: in out Positive) return Positive is
     
     function Sum_Of_Digits(N: Natural) return Natural is

( if N = 0 then 0 else ((N mod 10) + Sum_Of_Digits(N / 10)) );

  begin
     while not (N mod Sum_Of_Digits(N) = 0) loop

N := N + 1;

     end loop;
     return N;
  end Next;
  
  Current: Positive := 1;
  

begin

  for I in 1 .. 20 loop
     Ada.Text_IO.Put(Integer'Image(Next(Current)));
     Current := Current + 1;
  end loop;
  Current := 1000 + 1; 
  Ada.Text_IO.Put_Line(" ..." & Integer'Image(Next(Current)));

end Harshad;</lang>

Output:
 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002

AutoHotkey

<lang AutoHotkey>H := [] n := 1

Loop n := (H[A_Index] := NextHarshad(n)) + 1 until H[H.MaxIndex()] > 1000

Loop, 20 Out .= H[A_Index] ", "

MsgBox, % Out ". . . " H[H.MaxIndex()]

NextHarshad(n) { Loop, { Loop, Parse, n sum += A_LoopField if (!Mod(n, sum)) return n n++, sum := "" } }</lang>

Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, . . . 1002

AWK

<lang AWK>#!/usr/bin/awk -f BEGIN { k=0; n=0; printf("First twenty Harshad numbers are:\n "); while (k<20) { if (isharshad(++n)) { printf("%i ",n); ++k; } } n = 1000; while (!isharshad(++n)); printf("\nFirst Harshad number larger than 1000 is \n %i\n",n); }

function isharshad(n) { s = 0; for (i=0; i<length(n); ) { s+=substr(n,++i,1); } return !(n%s); }</lang>

Output:
First twenty Harshad numbers are:
   1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 
First Harshad number larger than 1000 is 
   1002

BBC BASIC

<lang bbcbasic> I%=1:CNT%=0

     WHILE TRUE
       IF FNHarshad(I%) THEN
         IF CNT%<20 PRINT ;I%;" ";:CNT%+=1
         IF I%>1000 PRINT ;I%:EXIT WHILE
       ENDIF
       I%+=1
     ENDWHILE
     END
     
     DEF FNHarshad(num%)
     LOCAL sum%,tmp%
     tmp%=num%
     sum%=0
     WHILE (tmp%>0)
       sum%+=tmp% MOD 10
       tmp%/=10
     ENDWHILE
     =(num% MOD sum%)=0</lang>
Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002

C

<lang C>#include <stdio.h>

static int digsum(int n) {

   int sum = 0;
   do { sum += n % 10; } while (n /= 10);
   return sum;

}

int main(void) {

   int n, done, found;
   for (n = 1, done = found = 0; !done; ++n) {
       if (n % digsum(n) == 0) {
           if (found++ < 20) printf("%d ", n);
           if (n > 1000) done = printf("\n%d\n", n);
       }
   }
   return 0;

}</lang>

Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 
1002

C#

<lang csharp> using System; using System.Collections.Generic;

namespace Harshad {

   class Program
   {
       public static bool IsHarshad(int n)
       {
           char[] inputChars = n.ToString().ToCharArray();
           IList<byte> digits = new List<byte>();
           foreach (char digit in inputChars)
           {
               digits.Add((byte)Char.GetNumericValue(digit));
           }
           if (n < 1)
           {
               return false;
           }
           int sum = 0;
           foreach (byte digit in digits)
           {
               sum += digit;
           }
           return n % sum == 0;
       }
       static void Main(string[] args)
       {
           int i = 1;
           int count = 0;
           while (true)
           {
               if (IsHarshad(i))
               {
                   count++;
                   if (count <= 20)
                   {
                       Console.Write(string.Format("{0} ", i));
                   }
                   else if (i > 1000)
                   {
                       Console.Write(string.Format("{0} ", i));
                       break;
                   }
               }
               i++;
           }
           Console.ReadKey();
       }
   }

} </lang>

Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002

C++

<lang cpp>#include <vector>

  1. include <iostream>

int sumDigits ( int number ) {

  int sum = 0 ;
  while ( number != 0 ) {
     sum += number % 10 ;
     number /= 10 ;
  }
  return sum ;

}

bool isHarshad ( int number ) {

  return number % ( sumDigits ( number ) ) == 0 ;

}

int main( ) {

  std::vector<int> harshads ;
  int i = 0 ;
  while ( harshads.size( ) != 20 ) {
     i++ ;
     if ( isHarshad ( i ) ) 

harshads.push_back( i ) ;

  }
  std::cout << "The first 20 Harshad numbers:\n" ;
  for ( int number : harshads )
     std::cout << number << " " ;
  std::cout << std::endl ;
  int start = 1001 ;
  while ( ! ( isHarshad ( start ) ) ) 
     start++ ;
  std::cout << "The smallest Harshad number greater than 1000 : " << start << '\n' ;
  return 0 ;

}</lang>

Output:
The first 20 Harshad numbers:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 
The smallest Harshad number greater than 1000 : 1002

Clojure

<lang Clojure>(defn digsum [n acc]

 (if (zero? n) acc
     (digsum (quot n 10) (+ acc (mod n 10)))))

(let [harshads (filter

                #(zero? (mod % (digsum % 0)))
                (iterate inc 1))]
 (prn (take 20 harshads))
 (prn (first (filter #(> % 1000) harshads))))</lang>
Output:
(1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42)
1002



COBOL

Works with: OpenCOBOL version 1.1

<lang cobol>identification division. program-id. harshad. environment division. data division. working-storage section.

  • > for storing first 20 harshad-niven numbers

01 harshads.

   03  harshad pic 9(5)    occurs 20 times indexed by niven.
  • > numbers tested for harshad-niven-ness.

01 first-num pic 9(5). 01 second-num pic 9(5).

  • > loop counter

01 i pic 9(5).

  • > for calculating sum of digits

01 div pic 9(5). 01 mod pic 9(5). 01 tot pic 9(5).

  • > for harshad-niven calculation and display

01 harshad-div pic 9(5). 01 harshad-mod pic 9(5).

   88  evenly-divisible    value 0.

01 harshad-disp pic zzzz9. 01 harshad-result pic 9(5).

  • > for selecting what to do with results of harshad calculation

01 pass pic 9.

   88  first-pass  value 1.
   88  second-pass value 2.
   

procedure division. 10-main section.

   move 1 to pass.
   set niven to 1.
   perform 20-calculate-harshad with test before varying first-num from 1 by 1 until niven = 21.
   
   move 2 to pass.
   move first-num to second-num.
   perform 20-calculate-harshad with test after varying first-num from second-num by 1 until harshad-result > 1000.
   
   perform with test after varying i from 1 by 1 until i = 20
       move harshad(i) to harshad-disp
       display function trim(harshad-disp) space with no advancing
   end-perform.
   
   move harshad-result to harshad-disp.
   display "... " function trim(harshad-disp).
   stop run.
   

20-calculate-harshad.

   move first-num to div.
   move zero to harshad-result.
   perform 100-calculate-sum-of-digits.
   divide first-num by tot giving harshad-div remainder harshad-mod.
   if evenly-divisible
       if first-pass
           move first-num to harshad(niven)
           set niven up by 1
       else
           move first-num to harshad-result
       end-if
   end-if.
   exit paragraph.
       

100-calculate-sum-of-digits.

   move zero to tot.
   perform with test after until div = 0
       divide div by 10 giving div remainder mod
       add mod to tot
   end-perform.
   *> if tot >= 10
   *>  move tot to div
   *>  go to 100-calculate-sum-of-digits
   *> end-if.
   exit paragraph.
   </lang>

ColdFusion

<lang cfm> <Cfset harshadNum = 0> <Cfset counter = 0>

<Cfloop condition="harshadNum lte 1000">

 <Cfset startnum = harshadNum + 1>
 <Cfset digits = 0>
 <Cfset harshad = 0>
 
 <Cfloop condition="Harshad eq 0">
 
   <Cfset current_i = startnum>
   <Cfset digits = 0>
   
   <cfloop condition="len(current_i) gt 1">
     <Cfset digit = left(current_i, 1)>
     <Cfset current_i = right(current_i, len(current_i)-1)>
     <Cfset digits = digits + digit>
   </cfloop>
   <Cfset digits = digits + current_i>
   
   <Cfif Startnum MOD digits eq 0>
     <Cfset harshad = 1>
   <Cfelse>
     <cfset startnum = startnum + 1>
   </Cfif>
   
 </Cfloop>
 
 <cfset harshadNum = startnum>
 <Cfset counter = counter + 1>
 
 <Cfif counter lte 20>
   <Cfoutput>#harshadNum# </Cfoutput>
 </Cfif>

</Cfloop>

<Cfoutput>... #harshadNum# </Cfoutput> </lang>

Common Lisp

<lang lisp>(defun harshadp (n)

 (zerop (rem n (digit-sum n))))

(defun digit-sum (n &optional (a 0))

 (cond ((zerop n) a)

(t (digit-sum (floor n 10) (+ a (rem n 10))))))

(defun list-harshad (n &optional (i 1) (lst nil))

 "list the first n Harshad numbers starting from i (default 1)"
 (cond ((= (length lst) n) (reverse lst))

((harshadp i) (list-harshad n (+ i 1) (cons i lst)))

(t (list-harshad n (+ i 1) lst))))</lang>

Output:
CL-USER> (list-harshad 20)
(1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42)
CL-USER> (list-harshad 1 1001)
(1002)

D

<lang d>void main() {

   import std.stdio, std.algorithm, std.range, std.conv;
   enum digSum = (int n) => n.text.map!(d => d - '0').sum;
   enum harshads = iota(1, int.max).filter!(n => n % digSum(n) == 0);
   harshads.take(20).writeln;
   harshads.filter!(h => h > 1000).front.writeln;

}</lang>

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
1002


Eiffel

<lang eiffel> note description : "project application root class" date  : "$October 10, 2014$" revision  : "$Revision$"

class NIVEN_SERIES

create make

feature make local number : INTEGER count : INTEGER last : BOOLEAN do number := 1

from number := 1 last := false

until last = true

loop

if (number \\ sum_of_digits(number) = 0) then count := count + 1

if (count <= 20 ) then print("%N") print(number) end

if (number > 1000) then print("%N") print(number) last := true end end

number := number + 1 end end

sum_of_digits(no:INTEGER):INTEGER

local sum : INTEGER num : INTEGER do sum := 0

from num := no

until num = 0

loop sum := sum + num \\ 10 num := num // 10 end

Result := sum end end

</lang>

Output:
1
2
3
4
5
6
7
8
9
10
12
18
20
21
24
27
30
36
40
42
1002

Erlang

<lang Erlang> -module( harshad ).

-export( [greater_than/1, sequence/1, task/0] ).

greater_than( N ) when N >= 1 ->

       greater_than( 2, N, acc(1, {0, []}) ).

sequence( Find_this_many ) when Find_this_many >= 1 ->

       sequence( 2, Find_this_many, acc(1, {0, []}) ).

task() ->

       io:fwrite( "~p~n", [sequence(20)] ),
       io:fwrite( "~p~n", [greater_than(1000)] ).


acc( N, Acc ) -> acc( N rem lists:sum([X - $0|| X <- erlang:integer_to_list(N)]), N, Acc ).

acc( 0, N, {Found, Acc} ) -> {Found + 1, [N | Acc]}; acc( _Reminder, _N, Acc ) -> Acc.

greater_than( _N, Find, {_, [Found | _T]} ) when Found > Find -> Found; greater_than( N, Find, Acc ) -> greater_than( N + 1, Find, acc(N, Acc) ).

sequence( _N, Found, {Found, Acc} ) -> lists:reverse( Acc ); sequence( N, Find, Acc ) -> sequence( N + 1, Find, acc(N, Acc) ). </lang>

Output:
39> harshad:task().
[1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
1002

F#

<lang fsharp>let divides d n =

   match bigint.DivRem(n, d) with
   | (_, rest) -> rest = 0I

let splitToInt (str:string) = List.init str.Length (fun i -> ((int str.[i]) - (int "0".[0])))

let harshads =

   let rec loop n = seq {
       let sum = List.fold (+) 0 (splitToInt (n.ToString()))
       if divides (bigint sum) n then yield n
       yield! loop (n + 1I)
   }
   loop 1I

[<EntryPoint>] let main argv =

   for h in (Seq.take 20 harshads) do printf "%A " h
   printfn ""
   printfn "%A" (Seq.find (fun n -> n > 1000I) harshads)
   0</lang>
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002

FBSL

The INITIALIZE routine fills a dynamic array with all we need, even the ellipsis. <lang qbasic>#APPTYPE CONSOLE

CLASS harshad

   PRIVATE:
   memo[]
   
   SUB INITIALIZE()
       DIM i = 1, c
       DO
           IF isNiven(i) THEN
               c = c + 1
               memo[c] = i
           END IF
           i = i + 1
           IF c = 20 THEN EXIT DO
       LOOP
       memo[] = "..."
       i = 1000
       WHILE NOT isNiven(INCR(i)): WEND
       memo[] = i
   END SUB
   
   FUNCTION isNiven(n)
       RETURN NOT (n MOD sumdigits(n))
   END FUNCTION
   
   FUNCTION sumdigits(n)
       DIM num = n, m, sum
       WHILE num
           sum = sum + num MOD 10
           num = num \ 10
       WEND
       RETURN sum
   END FUNCTION
   
   PUBLIC:
   METHOD Yield()
       FOREACH DIM e IN memo
           PRINT e, " ";
       NEXT
   END METHOD

END CLASS

DIM niven AS NEW harshad niven.Yield()

PAUSE </lang>

Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002
Press any key to continue...

Fortran

Please observe compilation on GNU/linux system and output from run are in the comments at the START of the FORTRAN 2003 source. The 1--20 loop idea was stolen from the ada solution. Thank you. <lang FORTRAN> !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Tue May 21 13:15:59 ! !a=./f && make $a && $a < unixdict.txt !gfortran -std=f2003 -Wall -ffree-form f.f03 -o f ! 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002 ! !Compilation finished at Tue May 21 13:15:59

program Harshad

 integer :: i, h = 0
 do i=1, 20
   call nextHarshad(h)
   write(6, '(i5)', advance='no') h
 enddo
 h = 1000
 call nextHarshad(h)
 write(6, '(i5)') h

contains

 subroutine nextHarshad(h) ! alter input integer h to be the next greater Harshad number.
   integer, intent(inout) :: h
   h = h+1 ! bigger
   do while (.not. isHarshad(h))
     h = h+1
   end do
 end subroutine nextHarshad
 logical function isHarshad(a)
   integer, intent(in) :: a
   integer :: mutable, digit_sum
   isHarshad = .false.
   if (a .lt. 1) return ! false if a < 1
   mutable = a
   digit_sum = 0
   do while (mutable /= 0)
     digit_sum = digit_sum + mod(mutable, 10)
     mutable = mutable / 10
   end do
   isHarshad = 0 .eq. mod(a, digit_sum)
 end function isHarshad

end program Harshad </lang>

Frink

<lang frink> isHarshad[n] := n mod sum[integerDigits[n]] == 0

c = 0 i = 1 while c<20 {

  if isHarshad[i]
  {
     c = c + 1
     println[i]
  }
  i = i + 1

}

println[] i = 1000

do

  i = i + 1

while ! isHarshad[i]

println[i] </lang>

Output:
1
2
3
4
5
6
7
8
9
10
12
18
20
21
24
27
30
36
40
42

1002

Go

<lang go>package main

import "fmt"

type is func() int

func newSum() is {

   var ms is
   ms = func() int {
       ms = newSum()
       return ms()
   }
   var msd, d int
   return func() int {
       if d < 9 {
           d++
       } else {
           d = 0
           msd = ms()
       }
       return msd + d
   }

}

func newHarshard() is {

   i := 0
   sum := newSum()
   return func() int {
       for i++; i%sum() != 0; i++ {
       }
       return i
   }

}

func main() {

   h := newHarshard()
   fmt.Print(h())
   for i := 1; i < 20; i++ {
       fmt.Print(" ", h())
   }
   fmt.Println()
   h = newHarshard()
   n := h()
   for ; n <= 1000; n = h() {
   }
   fmt.Println(n)

}</lang>

Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002

Haskell

<lang haskell>import Data.Char (ord)

main = do print $ take 20 harshads

         print $ head $ filter (> 1000) harshads
   where digsum = sum . map ((48 -) . ord) . show
         harshads = filter (\n -> mod n (digsum n) == 0) [1..]</lang>
Output:
[1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
1002

Icon and Unicon

<lang unicon>procedure main(A)

   limit := integer(A[1]) | 20
   every writes(niven(seq())\limit," ")
   writes("... ")
   write(niven(seq(1001))\1)

end

procedure niven(n)

   n ? {s := 0; while s +:= move(1)}
   if (n%s) = 0 then return n

end</lang>

Output:
->ns
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002
->

J

<lang J>Until =: 2 : 'u^:(-.@:v)^:_' isHarshad =: 0 = ] |~ [: +/ #.inv NB. BASE isHarshad N assert 1 0 -: 10 isHarshad&> 42 38 nextHarshad =: (>: Until (10&isHarshad))@:>: assert 45 -: nextHarshad 42 assert 3 4 5 -: nextHarshad&> 2 3 4 assert 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 -: (, nextHarshad@:{:)Until (20 = #) 1 assert 1002 -: nextHarshad 1000


  NB. next Harshad number in base 6.  Input and output are in base 6.
  NB. Verification left to you, gentle programmer.
  nextHarshad_base_6 =: (>: Until (6&isHarshad))@:>:
  6#.inv nextHarshad_base_6 6b23235

2 3 2 5 3 </lang>

Java

Works with: Java version 1.5+

<lang java5>public class Harshad{

   private static long sumDigits(long n){
       long sum = 0;
       for(char digit:Long.toString(n).toCharArray()){
           sum += Character.digit(digit, 10);
       }
       return sum;
   }
   public static void main(String[] args){
       for(int count = 0, i = 1; count < 20;i++){
           if(i % sumDigits(i) == 0){
               System.out.println(i);
               count++;
           }
       }
       System.out.println();
       for(int i = 1001; ; i++){
           if(i % sumDigits(i) == 0){
               System.out.println(i);
               break;
           }
       }
   }

}</lang>

Output:
1
2
3
4
5
6
7
8
9
10
12
18
20
21
24
27
30
36
40
42

1002

jq

<lang jq>def is_harshad:

def digits: tostring | [explode[] | ([.]| implode) | tonumber];
if . >= 1 then (. % (digits|add)) == 0
else false
end ;
  1. produce a stream of n Harshad numbers

def harshads(n):

 # [candidate, count]
 def _harshads:
   if .[0]|is_harshad then .[0], ([.[0]+1, .[1]-1]| _harshads)
   elif .[1] > 0 then [.[0]+1, .[1]] | _harshads
   else empty
   end;
 [1, n] | _harshads ;
  1. First Harshad greater than n where n >= 0

def harshad_greater_than(n):

 # input: next candidate
 def _harshad:
   if is_harshad then .
   else .+1 | _harshad
   end;
 (n+1) | _harshad ;
  1. Task:

[ harshads(20), "...", harshad_greater_than(1000)]</lang>

Output:
$ jq -n -c -f harshad.jq
[1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42,"...",1002]

Julia

<lang julia>isharshad(x) = x % sum(digits(x)) == 0 function harshads(n) h = Int[] i = 1 while length(h) < n isharshad(i) && push!(h,i) i+=1 end return h end</lang>

Output:
julia> harshads(20)
20-element Int32 Array:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 12
 18
 20
 21
 24
 27
 30
 36
 40
 42
julia> i = 1001; while !isharshad(i) i += 1 end; i
1002

LOLCODE

<lang LOLCODE>HAI 1.3

HOW IZ I digsummin YR num

   I HAS A digsum ITZ 0
   IM IN YR loop
       num, O RLY?
           YA RLY
               digsum R SUM OF digsum AN MOD OF num AN 10
               num R QUOSHUNT OF num AN 10
           NO WAI, FOUND YR digsum
       OIC
   IM OUTTA YR loop

IF U SAY SO

I HAS A found ITZ 0

IM IN YR finder UPPIN YR n

   I HAS A n ITZ SUM OF n AN 1
   I HAS A digsum ITZ I IZ digsummin YR n MKAY
   NOT MOD OF n AN digsum, O RLY?
       YA RLY
           DIFFRINT found AN BIGGR OF found AN 20, O RLY?
               YA RLY
                   VISIBLE n " "!
                   found R SUM OF found AN 1
           OIC
           DIFFRINT n AN SMALLR OF n AN 1000, O RLY?
               YA RLY, VISIBLE ":)" n, GTFO
           OIC
   OIC

IM OUTTA YR finder

KTHXBYE</lang>

Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 
1002

Mathematica

<lang mathematica>nextHarshad =

 NestWhile[# + 1 &, # + 1, ! Divisible[#, Total@IntegerDigits@#] &] &;

Print@Rest@NestList[nextHarshad, 0, 20]; Print@nextHarshad@1000;</lang>

Output:
{1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42}
1002


MATLAB / Octave

Define a testing function whether n is harshad or not <lang MATLAB>function v = isharshad(n) v = isinteger(n) && ~mod(n,sum(num2str(n)-'0')); end; </lang> Check numbers <lang MATLAB>k=1; n=1; while (k<=20) if isharshad(n) printf('%i ',n); k=k+1; end; n=n+1; end n = 1001; while ~isharshad(n) n=n+1; end; printf('\nFirst harshad number larger than 1000 is %i\n',n);</lang>

1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 
First harshad number larger than 1000 is 1002


MLite

<lang ocaml>fun sumdigits

                (0, n) = n
       |        (m, n) = sumdigits (m div 10, m rem 10) + n
       |        n      = sumdigits (n div 10, n rem 10)

fun is_harshad n = (n rem (sumdigits n) = 0)

fun next_harshad_after (n, ~1) = if is_harshad n then n else next_harshad_after (n + 1, ~1) | n = next_harshad_after (n + 1, ~1)

fun harshad

               (max, _, count > max, accum) = rev accum
       |       (max, here, count, accum) = 

if is_harshad here then

                               harshad (max, here + 1, count + 1, here :: accum)
                       else
                               harshad (max, here + 1, count, accum)
       |       max = harshad (max, 1, 1, [])

print "first twenty harshad numbers = "; println ` harshad 20; print "first harshad number after 1000 = "; println ` next_harshad_after 1000;</lang>

NetRexx

<lang netrexx>/* NetRexx ------------------------------------------------------------

  • 21.01.2014 Walter Pachl translated from ooRexx (from REXX version 1)
  • --------------------------------------------------------------------*/

options replace format comments java crossref symbols nobinary

 Parse Arg x y .                   /* get optional arguments:  X  Y */
 If x= Then x=20                 /* Not specified?  Use default   */
 If y= Then y=1000               /* "      "        "     "       */
 n=0                               /* Niven count                   */
 nl=                             /* Niven list.                   */
 Loop j=1 By 1 Until n=x           /* let's go Niven number hunting.*/
   If j//sumdigs(j)=0 Then Do      /* j is a Niven number           */
     n=n+1                         /* bump Niven count              */
     nl=nl j                       /* add to list.                  */
     End
   End
 Say 'first' n 'Niven numbers:'nl
 Loop j=y+1 By 1                   /* start with first candidate    */
   If j//sumdigs(j)=0 Then         /* j is a Niven number           */
     Leave
   End
 Say 'first Niven number >' y 'is:' j
 Exit

method sumdigs(n) public static returns Rexx

 sum=n.left(1)
 Loop k=2 To n.length()
   sum=sum+n.substr(k,1)
   End
 Return sum</lang>

output same as ooRexx's

Nim

<lang nim>import strutils

proc slice[T](iter: iterator(): T {.closure.}, sl): seq[T] =

 var result {.gensym.}: seq[int64] = @[]
 var i = 0
 for n in iter():
   if i > sl.b:
     break
   if i >= sl.a:
     result.add(n)
   inc i
 result

iterator harshad(): int64 {.closure.} =

 for n in 1 .. < int64.high:
   var sum = 0
   for ch in string($n):
     sum += parseInt("" & ch)
   if n mod sum == 0:
     yield n

echo harshad.slice 0 .. <20

for n in harshad():

 if n > 1000:
   echo n
   break</lang>
Output:
@[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
1002

Objeck

<lang objeck> class Harshad {

 function : Main(args : String[]) ~ Nil {
   count := 0;
   for(i := 1; count < 20; i += 1;) {
     if(i % SumDigits(i) = 0){
       "{$i} "->Print();
       count += 1;
     };
   };
   for(i := 1001; true; i += 1;) {
     if(i % SumDigits(i) = 0){
       "... {$i}"->PrintLine();
       break;
     };
   };
 }
 function : SumDigits(n : Int) ~ Int {
   sum := 0;
   do {
     sum += n % 10;
     n /= 10;
   } while(n <> 0);
   return sum;
 }

} </lang>

1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002

ooRexx

<lang oorexx>/* REXX ---------------------------------------------------------------

  • 21.01.2014 Walter Pachl modi-(simpli-)fied from REXX version 1
  • --------------------------------------------------------------------*/
 Parse Arg x y .                   /* get optional arguments:  X  Y */
 If x= Then x=20                 /* Not specified?  Use default   */
 If y= Then y=1000               /* "      "        "     "       */
 n=0                               /* Niven count                   */
 nl=                             /* Niven list.                   */
 Do j=1 Until n=x                  /* let's go Niven number hunting.*/
   If j//sumdigs(j)=0 Then Do      /* j is a Niven number           */
     n=n+1                         /* bump Niven count              */
     nl=nl j                       /* add to list.                  */
     End
   End
 Say 'first' n 'Niven numbers:'nl
 Do j=y+1                          /* start with first candidate    */
   If j//sumdigs(j)=0 Then         /* j is a Niven number           */
     Leave
   End
 Say 'first Niven number >' y 'is:' j
 Exit

sumdigs: Procedure /* compute sum of n's digits */

 Parse Arg n
 sum=left(n,1)
 Do k=2 To length(n)
   sum=sum+substr(n,k,1)
   End
 Return sum</lang>
Output:
first 20 Niven numbers: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
first Niven number > 1000 is: 1002

PARI/GP

Works with: PARI/GP version 2.6.0 and above

<lang parigp>isHarshad(n)=n%sumdigits(n)==0 n=0;k=20;while(k,if(isHarshad(n++),k--;print1(n", "))); n=1000;while(!isHarshad(n++),);print("\n"n)</lang>

Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 
1002

Pascal

Works with: Freepascal 2.6.4

Optimized for speed, by using the state before in IncSumDigit. <lang pascal>program Niven; const

 base = 10;

type

 tNum      = longword;{Uint64}

const

  cntbasedigits = trunc(ln(High(tNum))/ln(base))+1;

type

 tSumDigit = record
               sdNumber  : tNum;
               sdDigits  : array[0..cntbasedigits-1] of byte;
               sdSumDig  : byte;
               sdIsNiven : boolean;
             end;

function InitSumDigit( n : tNum):tSumDigit; var

 sd : tSumDigit;
 qt : tNum;
 i  : integer;

begin

 with sd do
 begin
   sdNumber:= n;
   fillchar(sdDigits,SizeOf(sdDigits),#0);
   sdSumDig :=0;
   sdIsNiven := false;
   i := 0;
   // calculate Digits und sum them up
   while n > 0 do
   begin
     qt := n div base;
     {n mod base}
     sdDigits[i] := n-qt*base;
     inc(sdSumDig,sdDigits[i]);
     n:= qt;
     inc(i);
   end;
   IF sdSumDig  >0 then
     sdIsNiven := (sdNumber MOD sdSumDig = 0);
 end;
 InitSumDigit:=sd;

end;

procedure IncSumDigit(var sd:tSumDigit); var

  i,d: integer;

begin

 i := 0;
 with sd do
 begin
   inc(sdNumber);
   repeat
     d := sdDigits[i];
     inc(d);
     inc(sdSumDig);
     //base-1 times the repeat is left here
     if d < base then
     begin
       sdDigits[i] := d;
       BREAK;
     end
     else
     begin
       sdDigits[i] := 0;
       dec(sdSumDig,base);
       inc(i);
     end;
   until i > high( sdDigits);
   sdIsNiven := (sdNumber MOD sdSumDig) = 0;
 end;

end;

var

 MySumDig : tSumDigit;
 ln : tNum;
 cnt: integer;

begin

 MySumDig:=InitSumDigit(0);
 cnt := 0;
 repeat
   IncSumDigit(MySumDig);
   IF MySumDig.sdIsNiven then
   begin
     write(MySumDig.sdNumber,'.');
     inc(cnt);
   end;
 until cnt >= 20;
 write('....');
 MySumDig:=InitSumDigit(1000);
 repeat
   IncSumDigit(MySumDig);
 until MySumDig.sdIsNiven;
 writeln(MySumDig.sdNumber,'.');

// searching for big gaps between two niven-numbers // MySumDig:=InitSumDigit(18879989100-276);

 MySumDig:=InitSumDigit(1);
 cnt := 0;
 ln:= MySumDig.sdNumber;
 repeat
   IncSumDigit(MySumDig);
   if MySumDig.sdIsNiven then
   begin
     IF cnt < (MySumDig.sdNumber-ln) then
     begin
       cnt :=(MySumDig.sdNumber-ln);
       writeln(ln,' --> ',MySumDig.sdNumber,'  d=',cnt);
     end;
     ln:= MySumDig.sdNumber;
   end;
 until MySumDig.sdNumber= High(tNum);

{ 689988915 --> 689989050 d=135 879987906 --> 879988050 d=144 989888823 --> 989888973 d=150 2998895823 --> 2998895976 d=153 ~ 24 Cpu-cycles per test i3- 4330 1..2^32-1} end.</lang> output:

1.2.3.4.5.6.7.8.9.10.12.18.20.21.24.27.30.36.40.42.....1002.

Perl

<lang perl>#!/usr/bin/perl use strict ; use warnings ; use List::Util qw ( sum ) ;

sub createHarshads {

  my @harshads ;
  my $number = 1 ;
  do {
     if ( $number % sum ( split ( // , $number ) ) == 0 ) {

push @harshads , $number ;

     }
     $number++ ;
  } until (  $harshads[ -1 ] > 1000 ) ;
  return @harshads ;

} my @harshadnumbers = createHarshads ; for my $i ( 0..19 ) {

  print "$harshadnumbers[ $i ]\n" ;

} print "The first Harshad number greater than 1000 is $harshadnumbers[ -1 ]!\n" ;</lang>

Output:
1
2
3
4
5
6
7
8
9
10
12
18
20
21
24
27
30
36
40
42
The first Harshad number greater than 1000 is 1002!

Perl 6

<lang perl6>constant harshad = grep { $_ %% [+] .comb }, 1 .. *;

say harshad[^20]; say harshad.first: * > 1000;</lang>

Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002

PL/I

<lang pli>*process source or(!) xref attributes;

niven: Proc Options(main);
/*********************************************************************
* 08-06.2013 Walter Pachl translated from Rexx
*                         with a slight improvement:  Do j=y+1 By 1;
*********************************************************************/
Dcl (ADDR,HBOUND,MOD,SUBSTR,VERIFY) Builtin;
Dcl SYSPRINT Print;
Dcl (x,y) dec fixed(8);
x=20;
y=1000;
Begin;
  Dcl (n(x),j) Dec Fixed(8);
  Dcl ni Bin Fixed(31) Init(0);
  Dcl result Char(100) Var Init();
loop:
  Do j=1 By 1;
    If mod(j,sumdigs(j))=0 Then Do;
      ni+=1;
      n(ni)=j;
      result=result!!' '!!d2c(j);
      If ni=x Then Leave loop;
      End;
    End;
  Put Edit('first 20 Niven numbers: ',result)(Skip,a,a);
  Do j=y+1 By 1;
    If mod(j,sumdigs(j))=0 Then
      Leave;
    End;
  Put Edit('first Niven number > ',d2c(y),' is: ',d2c(j))(Skip,4(a));
  End;
sumDigs: proc(z) Returns(Dec Fixed(3));
Dcl z Pic'(8)9';
Dcl d(8) Pic'9' Based(addr(z));
Dcl i Bin Fixed(31);
Dcl sd Dec Fixed(3) Init(0);
Do i=1 To hbound(d);
  sd+=d(i);
  End;
Return(sd);
End;
d2c: Proc(z) Returns(char(8) Var);
Dcl z Pic'(8)z';
Dcl p Bin Fixed(31);
p=verify(z,' ');
Return(substr(z,p));
End;
End;</lang>       
Output:
first 20 Niven numbers:  1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
first Niven number > 1000 is: 1002

Prolog

Works with SWI-Prolog and module lambda.pl written by Ulrich Neumerkel, it can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl. <lang Prolog>:- use_module(library(lambda)).

niven :- nb_setval(go, 1),

L = [1 | _], print_niven(L, 1), gen_niven(1, L).


print_niven([X|T], N) :- when(ground(X), ( ( nb_getval(go, 1) -> ( N < 20 -> writeln(X), N1 is N+1, print_niven(T, N1)  ; ( X > 1000 -> writeln(X), nb_setval(go, 0)  ; N1 is N+1, print_niven(T, N1)))  ; true))).


gen_niven(X, [N | T]) :- ( nb_getval(go, 1) -> X1 is X+1, sum_of_digit(X, S), ( X mod S =:= 0 -> N = X, gen_niven(X1, T)  ; gen_niven(X1, [N | T])) ; true).


sum_of_digit(N, S) :- number_chars(N, LC), maplist(\X^Y^number_chars(Y, [X]), LC, LN), sum_list(LN, S).

</lang>

Output:
 ?- niven.
1
2
3
4
5
6
7
8
9
10
12
18
20
21
24
27
30
36
40
1002
true.

Python

<lang python>>>> import itertools >>> def harshad(): for n in itertools.count(1): if n % sum(int(ch) for ch in str(n)) == 0: yield n


>>> list(itertools.islice(harshad(), 0, 20)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42] >>> for n in harshad(): if n > 1000: print(n) break


1002 >>> </lang>

Python: Functional

The for loop above could be changed to the following to find the number > 1000; in fact the harshad generator function could become a generator expression creating this more functional version: <lang python>>>> from itertools import count, islice >>> harshad = (n for n in count(1) if n % sum(int(ch) for ch in str(n)) == 0) >>> list(islice(harshad, 0, 20)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42] >>> next(x for x in harshad if x > 1000) 1002 >>> </lang>

Racket

<lang scheme>#lang racket

(define (digsum n)

 (for/sum ([c (number->string n)]) (string->number [string c])))
  

(define harshads

 (stream-filter (λ (n) (= (modulo n (digsum n)) 0)) (in-naturals 1)))

First 20 harshad numbers

(displayln (for/list ([i 20]) (stream-ref harshads i)))

First harshad greater than 1000

(displayln (for/first ([h harshads] #:when(> h 1000)) h))</lang>

Output:
(1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42)
1002

Different to the Scheme implementation in that it illustrates Racket's native iterators, and let-values with quotient/remainder: <lang racket>#lang racket (require math/number-theory) (define (digital-sum n)

 (let inner
   ((n n) (s 0))
   (if (zero? n) s
       (let-values ([(q r) (quotient/remainder n 10)])
         (inner q (+ s r))))))

(define (harshad-number? n)

 (and (>= n 1)
      (divides? (digital-sum n) n)))
find 1st 20 Harshad numbers

(for ((i (in-range 1 (add1 20)))

     (h (sequence-filter harshad-number? (in-naturals 1))))
 (printf "#~a ~a~%" i h))
find 1st Harshad number > 1000

(displayln (for/first ((h (sequence-filter harshad-number? (in-naturals 1001)))) h))</lang>

Output:
#1 1
#2 2
#3 3
#4 4
#5 5
#6 6
#7 7
#8 8
#9 9
#10 10
#11 12
#12 18
#13 20
#14 21
#15 24
#16 27
#17 30
#18 36
#19 40
#20 42
1002

REXX

These REXX examples allow the user to specify how many Niven numbers to list,
as well as find the first Niven number greater than a specified number.

generic version

<lang rexx>/*REXX program finds first X Niven numbers; also first Niven number > Y.*/ parse arg X Y . /*get optional arguments: X Y */ if X== then X=20 /*Not specified? Then use default*/ if Y== then Y=1000 /* " " " " " */

  1. =0; $= /*Niven# count; Niven# list. */
  do j=1  until #==X                  /*let's go Niven number hunting. */
  if j//sumDigs(j)\==0  then iterate  /*Not a Niven number?  Then skip.*/
  #=#+1;  $=$ j                       /*bump Niven# count; add to list.*/
  end   /*j*/

say 'first' X 'Niven numbers:' $

  do t=Y+1                            /*let's go Niven number searching*/
  if t//sumDigs(t)\==0  then iterate  /*Not a Niven number?  Then skip.*/
  if t>Y  then leave                  /*if greater than Y, go & show it*/
  end   /*t*/

say 'first Niven number >' Y " is: " t exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SUMDIGS subroutine──────────────────*/ sumDigs: procedure; parse arg ?; sum = left(?,1)

            do k=2  to length(?);     sum = sum+substr(?,k,1);  end /*k*/

return sum</lang>

Output:

when using the default inputs

first 20 Niven numbers:  1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
first Niven number > 1000  is:  1002

esoteric version

<lang rexx>/*REXX program finds first X Niven numbers; also first Niven number > Y.*/ parse arg X Y . /*get optional arguments: X Y */ if X== then X=20 /*Not specified? Then use default*/ if Y== then Y=1000 /* " " " " " */

  1. =0; $= /*Niven# count; Niven# list. */
  do j=1  until #==X                  /*let's go Niven number hunting. */
  if \isNiven(j)  then iterate        /*Not a Niven number?  Then skip.*/
  #=#+1;  $=$ j                       /*bump Niven# count; add to list.*/
  end   /*j*/

say 'first' X 'Niven numbers:' $

  do t=Y+1                            /*let's go Niven number searching*/
  if isNiven(t)  &  t>y  then leave   /*is a Niven #  AND  > Y, show it*/
  end   /*t*/

say 'first Niven number >' Y " is: " t exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────isNiven subroutine──────────────────*/ isNiven: procedure; parse arg ?; sum = left(?,1)

            do k=2  to length(?);     sum = sum+substr(?,k,1);  end /*k*/

return ?//sum==0</lang> output is the same as the first version

Ruby

Works with: Ruby version 2.1

Yielding from an iterator has more or less been neatly packaged into the #lazy method on Enumerable as of Ruby 2.0.
Enumerable#step method which doesn't have an argument corresponds from version 2.1. <lang Ruby>def digsum n

 n.to_s.chars.map(&:to_i).reduce(:+)

end

harshad = 1.step.lazy.select { |n| n % digsum(n) == 0 }

  1. harshad = (1..Float::INFINITY).lazy.select { |n| n % digsum(n) == 0 } # ver 2.0

p harshad.first(20) p harshad.find { |n| n > 1000 }</lang>

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
1002

Run BASIC

<lang runbasic>while count < 20

 h = h + 1
 if neven(h) = 0 then
   count = count + 1
   print count;": ";h
 end if

wend

h = 1000 while 1 = 1

 h = h + 1
 if neven(h) = 0 then
   print h
   exit while
 end if

wend

function neven(h) h$ = str$(h) for i = 1 to len(h$)

d = d + val(mid$(h$,i,1))

next i neven = h mod d end function</lang>

Output:
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
10: 10
11: 12
12: 18
13: 20
14: 21
15: 24
16: 27
17: 30
18: 36
19: 40
20: 42
1002

Scala

Library: Scala

<lang Scala>object Harshad extends App {

 import language.postfixOps
 import Stream._
 val fh: Stream[Int] => Stream[Int] = ints =>
   ints.head #:: fh((ints.tail) filter { i => i % (i.toString.map(_.asDigit) :\ 0)(_ + _) == 0 })
 val harshads = fh(from(1))
 println(harshads take 20 toList)
 println(harshads filter (_ > 1000) head)

}</lang>

Output:
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42)
1002

Scheme

<lang scheme>#!/usr/local/bin/gosh

Show the first 20 niven numbers and the
first one greater than 1000.

(define (main args)

   (display (iota-filtered 20 1 niven?))(newline)
   (display (iota-filtered 1 1001 niven?))(newline))
Return a list of length n
for numbers starting at start
that satisfy the predicate fn.

(define (iota-filtered n start fn)

   (let loop ((num start)(lst (list)))
       (if (= (length lst) n)
           lst
           (loop (+ 1 num) (if (fn num) (append lst (list num)) lst)))))
Is a number a niven number?

(define (niven? n)

   (and (> n 0) (= 0 (remainder n (sum-of-digits n)))))
Get the sum of the digits of a number.

(define (sum-of-digits n)

   (apply + (map string->number (map string (string->list (number->string n))))))

</lang>

Output:
(1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42)
(1002)

Seed7

<lang seed7>$ include "seed7_05.s7i";

const func integer: sumOfDigits (in var integer: num) is func

 result
   var integer: sum is 0;
 begin
   repeat
     sum +:= num rem 10;
     num := num div 10;
   until num = 0;
 end func;

const func integer: nextHarshadNum (inout integer: num) is func

 result
   var integer: harshadNumber is 0;
 begin
   while num mod sumOfDigits(num) <> 0 do
     incr(num);
   end while;
   harshadNumber := num;
 end func;

const proc: main is func

 local
   var integer: current is 1;
   var integer: count is 0;
 begin
   for count range 1 to 20 do
     write(nextHarshadNum(current) <& " ");
     incr(current);
   end for;
   current := 1001; 
   writeln(" ... " <& nextHarshadNum(current));
 end func;</lang>
Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42  ... 1002

Tcl

<lang tcl># Determine if the given number is a member of the class of Harshad numbers proc isHarshad {n} {

   if {$n < 1} {return false}
   set sum [tcl::mathop::+ {*}[split $n ""]]
   return [expr {$n%$sum == 0}]

}

  1. Get the first 20 numbers that satisfy the condition

for {set n 1; set harshads {}} {[llength $harshads] < 20} {incr n} {

   if {[isHarshad $n]} {

lappend harshads $n

   }

} puts [format "First twenty Harshads: %s" [join $harshads ", "]]

  1. Get the first value greater than 1000 that satisfies the condition

for {set n 1000} {![isHarshad [incr n]]} {} {} puts "First Harshad > 1000 = $n"</lang>

Output:
First twenty Harshads: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42
First Harshad > 1000 = 1002

Whitespace

<lang Whitespace>































</lang> This solution was generated from the pseudo-Assembly below. A live run is available for the inquiring skeptic. <lang asm>push 0 ; Harshad numbers found push 0 ; counter

0:  ; Increment the counter, call "digsum", branch on the modulus.

   push 1 add dup dup
   push 0 call 1 mod
       jz 2
       jump 0

1:  ; [n 0] => [digsum(n)]

   copy 1
   push 10 mod add swap
   push 10 div swap
   push 0 copy 2 sub
       jn 1
       slide 1 ret

2:  ; Should we print this Harshad number?

   push 1000 copy 1 sub jn 3 ; We're done if it's greater than 1000.
   swap push 1 add swap      ; Increment how many we've found so far.
   push 20 copy 2 sub jn 0   ; If we've already got 20, go back to the top.
   dup onum push 32 ochr     ; Otherwise, print it and a space.
   jump 0                    ; And /then/ go back to the top.

3:  ; Print the > 1000 Harshad number on its own line and exit clean.

   push 10 ochr onum pop push 10 ochr exit</lang>
Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 
1002

XPL0

<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations int H, C, N, S; \Harshad number, Counter, Number, Sum [H:= 1; C:= 0; loop [N:= H; S:= 0; \sum digits

       repeat  N:= N/10;
               S:= S + rem(0);
       until   N = 0;
       if rem(H/S) = 0 then    \Harshad no.is evenly divisible by sum of digits
               [if C < 20 then [IntOut(0, H);  ChOut(0, ^ );  C:= C+1];
               if H > 1000 then [IntOut(0, H);  CrLf(0);  quit];
               ];
       H:= H+1;
       ];

]</lang>

Output:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002

zkl

<lang zkl>fcn harshad(n){0==n%n.toString().split("").apply("toInt").sum()} [1..].tweak(fcn(n){if(not harshad(n))return(Void.Skip); n}).walk(20).println(); [1001..].tweak(fcn(n){if(not harshad(n))return(Void.Skip); n}).walk(1).println()</lang> Walkers are zkl iterators. [a..b] is a Walker from a to b. Walkers can be tweaked to transform the sequence they are walking. In this case, ignore non Harshad numbers. Then tell the walker to get 20 items from that [modified] sequence.

Output:
L(1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42)
L(1002)