Harshad or Niven series: Difference between revisions

add ABC
(Updated to compile with Nim 1.4. Simplified the code.)
(add ABC)
 
(63 intermediate revisions by 27 users not shown)
Line 32:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F is_harshad(n)
R n % sum(String(n).map(ch -> Int(ch))) == 0
 
Line 48:
I is_harshad(n)
print(n)
L.break</langsyntaxhighlight>
 
{{out}}
Line 57:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Harshad or Niven series - 01/05/2019
NIVEN CSECT
USING NIVEN,R13 base register
Line 113:
XDEC DS CL12 temp xdeco
REGEQU symbolic registers
END NIVEN</langsyntaxhighlight>
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002
</pre>
 
=={{header|8080 Assembly}}==
<syntaxhighlight lang="asm"> cpu 8086
org 100h
section .text
mov di,10 ; DI is the divisor to find digits
xor bp,bp ; Find first 20 Harshad numbers
mov cx,20
first: call next
mov ax,bp
call print
loop first
mov bp,1000 ; Find first Harshad number > 1000
call next ; .. fall through (print and stop)
mov ax,bp
;;; Print the number in AX
print: mov bx,buffer ; String buffer
.digit: xor dx,dx ; Divide by 10
div di
add dl,'0' ; Add ASCII 0 to remainder
dec bx
mov [bx],dl ; Store ASCII number
test ax,ax ; More digits?
jnz .digit
mov ah,9 ; Print string using DOS
mov dx,bx
int 21h
ret
;;; Let BP be the first Harshad number above BP
next: inc bp
mov ax,bp ; Keep a copy
xor bx,bx ; Sum
.digit: xor dx,dx ; Divide by 10
div di
add bx,dx ; Add remainder to sum
test ax,ax ; More digits?
jnz .digit
mov ax,bp ; Is it a Harshad number?
xor dx,dx
div bx
test dx,dx ; If not, try next number
jnz next
ret
section .data
db '*****'
buffer: db 13,10,'$'</syntaxhighlight>
{{out}}
<pre>1
2
3
4
5
6
7
8
9
10
12
18
20
21
24
27
30
36
40
42
1002</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO RETURN digit.sum n:
PUT 0 IN sum
WHILE n>0:
PUT sum + (n mod 10) IN sum
PUT floor (n/10) IN n
RETURN sum
 
HOW TO REPORT harshad n:
REPORT n mod digit.sum n = 0
 
HOW TO RETURN next.harshad n:
PUT n+1 IN n
WHILE NOT harshad n: PUT n+1 IN n
RETURN n
 
PUT 0 IN n
WRITE "First 20 Harshad numbers:"
FOR i IN {1..20}:
PUT next.harshad n IN n
WRITE n
WRITE /
WRITE "First Harshad number > 1000:", next.harshad 1000/</syntaxhighlight>
{{out}}
<pre>First 20 Harshad numbers: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First Harshad number > 1000: 1002</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">INT FUNC SumOfDigits(INT a)
INT sum
 
sum=0
WHILE a#0
DO
sum==+a MOD 10
a==/10
OD
RETURN (sum)
 
INT FUNC Next(INT a)
INT sum
 
DO
a==+1
sum=SumOfDigits(a)
UNTIL a MOD sum=0
OD
RETURN (a)
 
PROC Main()
INT i,a
 
a=0
FOR i=1 TO 20
DO
a=Next(a)
PrintI(a)
Put(32)
OD
Print("... ")
a=Next(1000)
PrintIE(a)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Harshad_or_Niven_series.png Screenshot from Atari 8-bit computer]
<pre>
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Harshad is
Line 146 ⟶ 282:
Current := 1000 + 1;
Ada.Text_IO.Put_Line(" ..." & Integer'Image(Next(Current)));
end Harshad;</langsyntaxhighlight>
{{out}}
<pre> 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
PROC digit sum = (INT i) INT :
BEGIN
Line 163 ⟶ 299:
FOR i FROM 1001 DO
(i %* digit sum (i) = 0 | printf (($g(0)l$, i)); stop) OD
END</langsyntaxhighlight>
{{out}}
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 1002
</pre>
 
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algolm">begin
integer function mod(a,b);
integer a,b;
mod := a-(a/b)*b;
 
integer function digitsum(n);
integer n;
digitsum :=
if n = 0 then 0
else mod(n,10) + digitsum(n/10);
integer function nextharshad(n);
integer n;
begin
integer ds;
loop:
n := n + 1;
ds := digitsum(n);
if mod(n, ds) <> 0 then go to loop;
nextharshad := n;
end;
 
integer i, n;
write("First 20 Harshad numbers:");
n := 0;
for i := 1 step 1 until 20 do
begin
n := nextharshad(n);
if mod(i,10)=1 then
write(n)
else
writeon(n);
end;
 
write("First Harshad number above 1000:", nextharshad(1000));
end</syntaxhighlight>
{{out}}
<pre>First 20 Harshad numbers:
1 2 3 4 5 6 7 8 9 10
12 18 20 21 24 27 30 36 40 42
First Harshad number above 1000: 1002</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin % find members of the Harshad/Niven series - numbers divisible by the sum of their digits %
% returns the next member of the series above n %
integer procedure nextHarshad ( integer value n ) ;
begin
integer h, s;
h := n;
while begin
integer v;
v := h := h + 1;
s := 0;
while v > 0 do begin
s := s + v rem 10;
v := v div 10
end while_v_gt_0 ;
h rem s not = 0
end do begin end;
h
end nextHarshad ;
integer h;
% show the first 20 members of the seuence %
write( "First 20 Harshad/Niven numbers:" );
h := 0;
for i := 1 until 20 do begin
h := nextHarshad( h );
writeon( i_w := 1, s_w := 0, " ", h )
end for_i ;
write( i_w := 1, s_w := 0, "First Harshad/Niven number > 1000: ", nextHarshad( 1000 ) );
end.</syntaxhighlight>
{{out}}
<pre>
First 20 Harshad/Niven numbers: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First Harshad/Niven number > 1000: 1002
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">(20∘↑,¯1∘↑)∘((⊢,((+∘1)⍣((0=+/∘(⍎¨⍕)|⊢)⊣)⊃∘⌽))⍣(1∊1000<⊣)),1</syntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002</pre>
 
=={{header|AppleScript}}==
===Idiomatic===
<langsyntaxhighlight lang="applescript">on nextHarshad(n)
if (n < 0) then set n to 0
repeat
Line 194 ⟶ 414:
set h to nextHarshad(1000)
 
return {harshads, h}</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42}, 1002}</langsyntaxhighlight>
 
===Functional===
 
Clicking together some generic functions, for a little more productivity and for easier refactoring, we can define the Harshad series as a filter over an infinite stream of integers.
<langsyntaxhighlight lang="applescript">
------------------ HARSHAD OR NIVEN SERIES -----------------
 
Line 491 ⟶ 711:
set my text item delimiters to dlm
s
end unlines</langsyntaxhighlight>
{{Out}}
<pre>First 20: -> [1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
 
First over 1000: -> 1002</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">harshad?: function [n] -> zero? n % sum digits n
harshads: select 1..1100 => harshad?
 
print ["First 20 harshad numbers:" first.n:20 harshads]
 
loop harshads 'h [
if h > 1000 [
print ["First harshad > 1000:" h]
break
]
]</syntaxhighlight>
 
{{out}}
 
<pre>First 20 harshad numbers: [1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42]
First harshad > 1000: 1002</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">H := []
n := 1
 
Line 518 ⟶ 757:
n++, sum := ""
}
}</langsyntaxhighlight>
{{out}}
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, . . . 1002</pre>
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
BEGIN {
k=0; n=0;
Line 544 ⟶ 783:
}
return !(n%s);
}</langsyntaxhighlight>
{{out}}
<pre>First twenty Harshad numbers are:
Line 552 ⟶ 791:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 589 ⟶ 828:
set /a tempcount+=1
goto strlengthloop
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 614 ⟶ 853:
First Harshad number greater than 1000: 1002
</pre>
 
=={{header|BASIC}}==
<syntaxhighlight lang="basic">10 DEFINT P,N,I,S
20 PRINT "First 20 Harshad numbers:"
30 P=0
40 N=0
50 N=N+1
60 S=0
70 I=N
80 S=S+I MOD 10
90 I=I\10
100 IF I THEN 80
110 IF N MOD S THEN 50
120 IF P<20 THEN P=P+1: PRINT N,
130 IF N<=1000 THEN 50
140 PRINT
150 PRINT "First Harshad number > 1000:";N</syntaxhighlight>
{{out}}
<pre>First 20 Harshad numbers:
1 2 3 4 5
6 7 8 9 10
12 18 20 21 24
27 30 36 40 42
 
First Harshad number > 1000: 1002</pre>
 
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="freebasic">
function sumDigitos(n)
if n < 0 then return 0
suma = 0
while n > 0
suma = suma + (n mod 10)
n = n \ 10
end while
return suma
end function
 
function isHarshad(n)
return n mod sumDigitos(n) = 0
end function
 
print "Los primeros 20 números de Harshad o Niven son:"
cuenta = 0
i = 1
 
do
if isHarshad(i) then
print i; " ";
cuenta += 1
end if
i += 1
until cuenta = 20
 
print : print
print "El primero de esos números por encima de 1000 es:"
i = 1001
 
do
if isHarshad(i) then
print i; " "
exit do
end if
i += 1
until false
end
</syntaxhighlight>
{{out}}
<pre>
Los primeros 20 números de Harshad o Niven son:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
 
El primero de esos números por encima de 1000 es:
1002
</pre>
 
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> I%=1:CNT%=0
WHILE TRUE
IF FNHarshad(I%) THEN
Line 634 ⟶ 951:
tmp%/=10
ENDWHILE
=(num% MOD sum%)=0</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let dsum(n) = n=0 -> 0, n rem 10 + dsum(n/10)
let next(n) = harshad(n+1) and harshad(n) = n rem dsum(n)=0 -> n, next(n)
 
let start() be
$( let n = 0
writes("First 20:")
for i = 1 to 20 do
$( n := next(n)
writef(" %N", n)
$)
writef("*NFirst above 1000: %N*N", next(1000))
$)</syntaxhighlight>
{{out}}
<pre>First 20: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First above 1000: 1002</pre>
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">45*1>::01-\>:55+%\vv\0<
>\1+^ + <|:/<+55<` :
^_>1-\:.v@1>\:0\`#v_+\^
>^1\,+55<.^_:#%$:#<"}"v
^!:\_ ^###< !`*8<</langsyntaxhighlight>
 
{{out}}
Line 667 ⟶ 1,003:
42
1002</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">SumDgt ← +´•Fmt-'0'˙
Niven ← 0=SumDgt|⊢
nivens ← Niven¨⊸/↕1100
⟨20↑nivens, ⊑(⊢>1000˙)⊸/nivens⟩</syntaxhighlight>
{{out}}
<pre>⟨ ⟨ 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ⟩ 1002 ⟩</pre>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
static int digsum(int n)
Line 690 ⟶ 1,034:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
Line 696 ⟶ 1,040:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 758 ⟶ 1,102:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002</pre>
 
===Shorter solution===
<langsyntaxhighlight lang="csharp">using System.Collections.Generic;
using static System.Linq.Enumerable;
using static System.Console;
Line 784 ⟶ 1,128:
for (; n > 0; n /= 10) yield return n % 10;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <vector>
#include <iostream>
 
Line 820 ⟶ 1,164:
std::cout << "The smallest Harshad number greater than 1000 : " << start << '\n' ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 829 ⟶ 1,173:
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(defn digsum [n acc]
(if (zero? n) acc
(digsum (quot n 10) (+ acc (mod n 10)))))
Line 837 ⟶ 1,181:
(iterate inc 1))]
(prn (take 20 harshads))
(prn (first (filter #(> % 1000) harshads))))</langsyntaxhighlight>
{{out}}
<pre>(1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42)
1002</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">digit_sum = proc (n: int) returns (int)
sum: int := 0
while n > 0 do
sum := sum + n // 10
n := n / 10
end
return (sum)
end digit_sum
 
harshads = iter (n: int) yields (int)
while true do
n := n + 1
if n // digit_sum(n) = 0 then yield(n) end
end
end harshads
 
start_up = proc ()
po: stream := stream$primary_output()
count: int := 0
stream$putl(po, "First 20 Harshad numbers: ")
for h: int in harshads(0) do
stream$putright(po, int$unparse(h), 3)
count := count + 1
if count = 20 then break end
end
stream$puts(po, "\nFirst Harshad number above 1000: ")
for h: int in harshads(1000) do
stream$putl(po, int$unparse(h))
break
end
end start_up</syntaxhighlight>
{{out}}
<pre>First 20 Harshad numbers:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First Harshad number above 1000: 1002</pre>
 
=={{header|COBOL}}==
{{works with|OpenCOBOL|1.1}}
<langsyntaxhighlight lang="cobol">identification division.
program-id. harshad.
environment division.
Line 922 ⟶ 1,305:
*> end-if.
exit paragraph.
</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm">
<Cfset harshadNum = 0>
<Cfset counter = 0>
Line 965 ⟶ 1,348:
 
<Cfoutput>... #harshadNum# </Cfoutput>
</syntaxhighlight>
</lang>
 
=={{header|Comal}}==
<syntaxhighlight lang="comal">0010 FUNC digit'sum(n)
0020 sum:=0
0030 WHILE n>0 DO sum:+n MOD 10;n:=n DIV 10
0040 RETURN sum
0050 ENDFUNC digit'sum
0060 //
0070 FUNC next'harshad(n)
0080 REPEAT
0090 n:+1
0100 UNTIL n MOD digit'sum(n)=0
0110 RETURN n
0120 ENDFUNC next'harshad
0130 //
0140 PRINT "First 20 Harshad numbers: "
0150 n:=0
0160 FOR i:=1 TO 20 DO
0170 n:=next'harshad(n)
0180 PRINT n;
0190 ENDFOR i
0200 PRINT
0210 PRINT "First Harshad number above 1000:";next'harshad(1000)
0220 END</syntaxhighlight>
{{out}}
<pre>First 20 Harshad numbers:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First Harshad number above 1000: 1002</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun harshadp (n)
(zerop (rem n (digit-sum n))))
 
Line 979 ⟶ 1,390:
(cond ((= (length lst) n) (reverse lst))
((harshadp i) (list-harshad n (+ i 1) (cons i lst)))
(t (list-harshad n (+ i 1) lst))))</langsyntaxhighlight>{{out}}
<pre>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)
Line 985 ⟶ 1,396:
(1002)
</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">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();</syntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">for i = 1 to 1002
 
let t = i
let s = 0
 
do
 
let s = s + t % 10
let t = int(t / 10)
 
wait
 
loop t > 0
 
if i % s = 0 and (c < 20 or i > 1000) then
 
let c = c + 1
print c, " : ", i
 
endif
 
next i</syntaxhighlight>
{{out| Output}}<pre>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
21 : 1002</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">harshad = 1.step.select { |n| n % n.to_s.chars.sum(&.to_i) == 0 }
puts "The first 20 harshard numbers are: \n#{ harshad.first(20).to_a }"
puts "The first harshard number > 1000 is #{ harshad.find { |n| n > 1000 } }"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,001 ⟶ 1,497:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.conv;
 
Line 1,009 ⟶ 1,505:
harshads.take(20).writeln;
harshads.filter!(h => h > 1000).front.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
1002</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Harshad_or_Niven_series#Pascal Pascal].
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec dsum(word n) word:
word r;
r := 0;
while n ~= 0 do
r := r + n % 10;
n := n / 10
od;
r
corp
 
proc nonrec next_harshad(word n) word:
while
n := n + 1;
n % dsum(n) ~= 0
do od;
n
corp
 
proc nonrec main() void:
word n;
byte i;
write("First 20:");
n := 0;
for i from 1 upto 20 do
n := next_harshad(n);
write(" ", n)
od;
writeln();
write("First above 1000: ", next_harshad(1000))
corp</syntaxhighlight>
{{out}}
<pre>First 20: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First above 1000: 1002</pre>
 
=={{header|EasyLang}}==
{{trans|FreeBASIC}}
<syntaxhighlight>
func digsum n .
while n > 0
sum += n mod 10
n = n div 10
.
return sum
.
func isHarshad n .
return if n mod digsum n = 0
.
i = 1
repeat
if isHarshad i = 1
write i & " "
cnt += 1
.
until cnt = 20
i += 1
.
print ""
i = 1001
while isHarshad i = 0
i += 1
.
print i
</syntaxhighlight>
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define (harsh? n)
(zero? (modulo n
Line 1,030 ⟶ 1,598:
(for ((n H)) #:break (> n 1000) => n)
→ 1002
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
note
description : "project application root class"
Line 1,111 ⟶ 1,679:
end
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,138 ⟶ 1,706:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Harshad do
def series, do: Stream.iterate(1, &(&1+1)) |> Stream.filter(&(number?(&1)))
Line 1,149 ⟶ 1,717:
IO.inspect Harshad.series |> Enum.take(20)
 
IO.inspect Harshad.series |> Stream.drop_while(&(&1 <= 1000)) |> Enum.take(1) |> hd</langsyntaxhighlight>
 
{{out}}
Line 1,158 ⟶ 1,726:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( harshad ).
 
Line 1,185 ⟶ 1,753:
sequence( _N, Found, {Found, Acc} ) -> lists:reverse( Acc );
sequence( N, Find, Acc ) -> sequence( N + 1, Find, acc(N, Acc) ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,198 ⟶ 1,766:
A somewhat more simple approach. Somewhat more efficient since it produces the partial list 23 times for the 20 element case whereas the above does so 36 or 37 times.
 
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(harshad).
-export([main/0,harshad/1,seq/1]).
Line 1,229 ⟶ 1,797:
io:format("seq(20): ~w~n", [ seq(20) ]),
io:format("gt(1000): ~w~n", [ gt(1000,[]) ]).
</syntaxhighlight>
</lang>
<pre>
Line 1,238 ⟶ 1,806:
 
</pre>
 
=={{header|Excel}}==
===LAMBDA===
 
Binding the names '''nextHarshad''', and '''harshads''' to the following lambda expressions in the Name Manager of the Excel WorkBook:
 
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
 
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">nextHarshad
=LAMBDA(n,
UNTIL(
LAMBDA(x,
0 = MOD(x, decDigitSum(x))
)
)(
LAMBDA(x, 1 + x)
)(1 + n)
)
 
harshads
=LAMBDA(n,
UNTIL(
LAMBDA(xs, n = ROWS(xs))
)(
LAMBDA(xs,
APPENDROWS(xs)(
nextHarshad(
INDEX(LASTROW(xs), 1)
)
)
)
)(
{1}
)
)</syntaxhighlight>
 
and also assuming the following generic bindings in the Name Manager for the WorkBook:
 
<syntaxhighlight lang="lisp">APPENDROWS
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, ROWS(xs),
rowIndexes, SEQUENCE(nx + ROWS(ys)),
colIndexes, SEQUENCE(
1,
MAX(COLUMNS(xs), COLUMNS(ys))
),
 
IFERROR(
IF(rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes),
INDEX(ys, rowIndexes - nx, colIndexes)
),
NA()
)
)
)
)
 
 
CHARSROW
=LAMBDA(s,
MID(s,
SEQUENCE(1, LEN(s), 1, 1),
1
)
)
 
 
decDigitSum
=LAMBDA(n,
SUM(VALUE(CHARSROW(n)))
)
 
 
LASTROW
=LAMBDA(xs,
INDEX(
xs,
ROWS(xs),
SEQUENCE(1, COLUMNS(xs), 1, 1)
)
)
 
 
UNTIL
=LAMBDA(p,
LAMBDA(f,
LAMBDA(x,
IF(p(x),
x,
UNTIL(p)(f)(f(x))
)
)
)
)</syntaxhighlight>
 
{{Out}}
 
Next Harshad after lower limit:
 
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="2" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=nextHarshad(A2)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="font-weight:bold" | First above
| style="font-weight:bold" | Harshad term
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right" | 1000
| style="text-align:right; background-color:#cbcefb" | 1002
|}
 
Sequence of Harshads:
 
(The single formula in cell B2 defines an array which populates the whole range '''B2:B21''')
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="2" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=harshads(20)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="font-weight:bold" | Number of terms
| style="font-weight:bold" | Harshads
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right" | 20
| style="text-align:right; background-color:#cbcefb" | 1
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
|
| style="text-align:right" | 2
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
|
| style="text-align:right" | 3
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
|
| style="text-align:right" | 4
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
|
| style="text-align:right" | 5
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
|
| style="text-align:right" | 6
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
|
| style="text-align:right" | 7
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 9
|
| style="text-align:right" | 8
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 10
|
| style="text-align:right" | 9
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 11
|
| style="text-align:right" | 10
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 12
|
| style="text-align:right" | 12
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 13
|
| style="text-align:right" | 18
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 14
|
| style="text-align:right" | 20
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 15
|
| style="text-align:right" | 21
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 16
|
| style="text-align:right" | 24
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 17
|
| style="text-align:right" | 27
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 18
|
| style="text-align:right" | 30
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 19
|
| style="text-align:right" | 36
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 20
|
| style="text-align:right" | 40
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 21
|
| style="text-align:right" | 42
|}
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let divides d n =
match bigint.DivRem(n, d) with
| (_, rest) -> rest = 0I
Line 1,259 ⟶ 2,044:
printfn ""
printfn "%A" (Seq.find (fun n -> n > 1000I) harshads)
0</langsyntaxhighlight>
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: math.text.utils lists lists.lazy ;
 
: niven? ( n -- ? ) dup 1 digit-groups sum mod 0 = ;
Line 1,274 ⟶ 2,059:
 
20 first-n-niven .
1000 next-niven .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,283 ⟶ 2,068:
=={{header|FBSL}}==
The INITIALIZE routine fills a dynamic array with all we need, even the ellipsis.
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
CLASS harshad
Line 1,330 ⟶ 2,115:
 
PAUSE
</syntaxhighlight>
</lang>
{{out}}
<pre>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...</pre>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 S N=0
01.20 S P=0
01.30 D 3
01.40 I (19-P)1.7
01.50 T %4,N,!
01.60 S P=P+1
01.70 I (N-1001)1.3
01.80 T N,!
01.90 Q
 
02.10 S A=0
02.20 S B=N
02.30 S C=FITR(B/10)
02.40 S A=A+B-C*10
02.50 S B=C
02.60 I (-B)2.3
 
03.10 S N=N+1
03.20 D 2
03.30 I (FITR(N/A)*A-N)3.1</syntaxhighlight>
{{out}}
<pre>= 1
= 2
= 3
= 4
= 5
= 6
= 7
= 8
= 9
= 10
= 12
= 18
= 20
= 21
= 24
= 27
= 30
= 36
= 40
= 42
= 1002</pre>
 
=={{header|Fortran}}==
Line 1,340 ⟶ 2,169:
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.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 13:15:59
Line 1,385 ⟶ 2,214:
 
end program Harshad
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function sumDigits(n As Integer) As Integer
Line 1,431 ⟶ 2,260:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,443 ⟶ 2,272:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
isHarshad[n] := n mod sum[integerDigits[n]] == 0
 
Line 1,466 ⟶ 2,295:
 
println[i]
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,493 ⟶ 2,322:
1002
</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn Harshad( num as long ) as long
long sum = 0, tmp = num
while ( tmp > 0 )
sum += tmp mod 10
tmp = tmp / 10
wend
end fn = (num mod sum) = 0
 
local fn DoIt
long i = 1, cnt = 0
print "First 20 in series: ";
while (1)
if fn Harshad( i )
if ( cnt < 20 ) then print ; i; " "; : cnt++
if ( i > 1000 ) then print : print "First above 1000: "; i : exit while
end if
i++
wend
end fn
 
fn Doit
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
First 20 in series: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First above 1000: 1002
</pre>
 
 
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Harshad_numbers}}
 
'''Solution'''
 
[[File:Fōrmulæ - Harshad numbers 01.png]]
 
'''Test case 1.''' List the first 20 members of the sequence
 
[[File:Fōrmulæ - Harshad numbers 02.png]]
 
[[File:Fōrmulæ - Harshad numbers 03.png]]
 
'''Test case 2.''' List the first Harshad number greater than 1,000
 
[[File:Fōrmulæ - Harshad numbers 04.png]]
 
[[File:Fōrmulæ - Harshad numbers 05.png]]
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=9d814ce9936ed7fdce2a084004c437f4 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siCount, siLoop, siTotal, siCounter As Short
Dim sNo, sTemp As String
Line 1,523 ⟶ 2,409:
Print sNiven.Join(", ")
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,531 ⟶ 2,417:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,577 ⟶ 2,463:
}
fmt.Println(n)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,585 ⟶ 2,471:
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">
<lang Groovy>
​class HarshadNiven{ public static boolean find(int x)
{
Line 1,623 ⟶ 2,509:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,632 ⟶ 2,518:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char (digitToInt)
 
harshads :: [Int]
Line 1,640 ⟶ 2,526:
 
main :: IO ()
main = mapM_ print [take 20 harshads, [(head . filter (> 1000)) harshads]]</langsyntaxhighlight>
{{out}}
<pre>[1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
Line 1,647 ⟶ 2,533:
Or, as an alternative to string operations:
 
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
import Data.Tuple (swap)
import Data.Bool (bool)
Line 1,659 ⟶ 2,545:
 
main :: IO ()
main = mapM_ print $ [take 20, take 1 . dropWhile (<= 1000)] <*> [harshads]</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,667 ⟶ 2,553:
=={{header|Icon}} and {{header|Unicon}}==
 
<langsyntaxhighlight lang="unicon">procedure main(A)
limit := integer(A[1]) | 20
every writes(niven(seq())\limit," ")
Line 1,677 ⟶ 2,563:
n ? {s := 0; while s +:= move(1)}
if (n%s) = 0 then return n
end</langsyntaxhighlight>
 
{{out}}
Line 1,687 ⟶ 2,573:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Harshad.bas"
110 LET I=1:LET CNT=0
120 PRINT "First 20 Harshad numbers are:"
Line 1,706 ⟶ 2,592:
270 LOOP
280 LET HARSHAD=MOD(NUM,SUM)=0
290 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight Jlang="j">Until =: 2 : 'u^:(-.@:v)^:_'
isHarshad =: 0 = ] |~ [: +/ #.inv NB. BASE isHarshad N
assert 1 0 -: 10 isHarshad&> 42 38
Line 1,724 ⟶ 2,610:
' '-.~":6#.inv nextHarshad_base_6 6b23235
23253
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class Harshad{
private static long sumDigits(long n){
long sum = 0;
Line 1,751 ⟶ 2,637:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,778 ⟶ 2,664:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">function isHarshad(n) {
var s = 0;
var n_str = new String(n);
Line 1,802 ⟶ 2,688:
while (!isHarshad(++h));
console.log(h);
</syntaxhighlight>
</lang>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002</pre>
 
===ES6 with generator===
<syntaxhighlight lang="javascript">function* harshads (start) {
for (let n = start; true; n++) {
const sum = [...n.toString()].map(Number).reduce((a, b) => a + b)
if (n % sum === 0) {
yield n
}
}
}
 
const first20 = (() => {
const hs = harshads(1)
return [...Array(20)].map(() => hs.next().value)
})()
console.log("First 20:", ...first20)
 
const firstAfter1000 = harshads(1001).next().value
console.log("First after 1000:", firstAfter1000)</syntaxhighlight>
{{out}}
<pre>First 20: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First after 1000: 1002</pre>
 
===ES6===
One possible approach to functional composition:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,877 ⟶ 2,785:
firstOver1000: head(dropWhile(x => x <= 1000, nHarshads(1000)))
});
})();</langsyntaxhighlight>
{{Out}}
<pre>{
Line 1,906 ⟶ 2,814:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def is_harshad:
def digits: tostring | [explode[] | ([.]| implode) | tonumber];
if . >= 1 then (. % (digits|add)) == 0
Line 1,932 ⟶ 2,840:
 
# Task:
[ harshads(20), "...", harshad_greater_than(1000)]</langsyntaxhighlight>
{{Out}}
$ jq -n -c -f harshad.jq
Line 1,939 ⟶ 2,847:
=={{header|Julia}}==
{{works with|Julia|0.6}}
<langsyntaxhighlight lang="julia">isharshad(x) = x % sum(digits(x)) == 0
nextharshad(x) = begin while !isharshad(x+1) x += 1 end; return x + 1 end
 
Line 1,952 ⟶ 2,860:
 
println("First 20 harshad numbers: ", join(harshads(20), ", "))
println("First harshad number after 1001: ", nextharshad(1000))</langsyntaxhighlight>
 
{{out}}
Line 1,959 ⟶ 2,867:
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
/ sum of digits of an integer
sumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d}
Line 1,966 ⟶ 2,874:
/ Generate x Harshad numbers starting from y and display the list
hSeries: {harshad::();i:y;while[(x-#harshad)>0;:[isHarshad i; harshad::(harshad,i)]; i+:1];harshad}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,977 ⟶ 2,885:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
fun sumDigits(n: Int): Int = when {
Line 2,015 ⟶ 2,923:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,025 ⟶ 2,933:
1002
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def harshad?
{def harshad?.sum
{lambda {:n}
{if {W.empty? {W.rest :n}}
then {W.first :n}
else {+ {W.first :n}
{harshad?.sum {W.rest :n}}} }}}
{lambda {:n}
{= {% :n {harshad?.sum :n}} 0} }}
-> harshad?
 
{harshad? 12}
-> true
{harshad? 13}
-> false
 
{def harshads
{def harshads.loop
{lambda {:a :n :i}
{if {> {A.length :a} :n}
then :a
else {harshads.loop {if {harshad? :i}
then {A.addlast! :i :a}
else :a}
:n
{+ :i 1}} }}}
{lambda {:n}
{harshads.loop {A.new} :n 0} }}
-> harshads
 
{harshads 20}
-> [0,1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
 
{def firstharshadafter
{def firstharshadafter.loop
{lambda {:i}
{if {harshad? :i}
then :i
else {firstharshadafter.loop {+ :i 1}} }}}
{lambda {:n}
{firstharshadafter.loop {+ :n 1}} }}
-> firstharshadafter
 
{firstharshadafter 1000}
-> 1002
</syntaxhighlight>
 
=={{header|LOLCODE}}==
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
HOW IZ I digsummin YR num
Line 2,061 ⟶ 3,018:
IM OUTTA YR finder
 
KTHXBYE</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
Line 2,067 ⟶ 3,024:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function isHarshad(n)
local s=0
local n_str=tostring(n)
Line 2,095 ⟶ 3,052:
end
print(h)
</syntaxhighlight>
</lang>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
Line 2,101 ⟶ 3,058:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">nextHarshad =
NestWhile[# + 1 &, # + 1, ! Divisible[#, Total@IntegerDigits@#] &] &;
Print@Rest@NestList[nextHarshad, 0, 20];
Print@nextHarshad@1000;</langsyntaxhighlight>
{{out}}
<pre>{1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42}
1002</pre>
 
=={{header|MAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(A,B)
ENTRY TO REM.
FUNCTION RETURN A-A/B*B
END OF FUNCTION
INTERNAL FUNCTION(I)
ENTRY TO DSUM.
SUM = 0
REST = I
DIGIT WHENEVER REST.NE.0
SUM = SUM + REM.(REST,10)
REST = REST/10
TRANSFER TO DIGIT
END OF CONDITIONAL
FUNCTION RETURN SUM
END OF FUNCTION
INTERNAL FUNCTION(I)
ENTRY TO NEXT.
LOOP THROUGH LOOP, FOR NX=I+1, 1, REM.(NX,DSUM.(NX)).E.0
FUNCTION RETURN NX
END OF FUNCTION
PRINT COMMENT $ FIRST 20 HARSHAD NUMBERS:$
H = 0
N = 0
HARSHD WHENEVER N.LE.1000
N = NEXT.(N)
H = H + 1
WHENEVER H.LE.20, PRINT FORMAT HSHD, H, N
TRANSFER TO HARSHD
END OF CONDITIONAL
PRINT FORMAT THSND, N
VECTOR VALUES HSHD = $8HHARSHAD(,I2,4H) = ,I2*$
VECTOR VALUES THSND =
0 $34HFIRST HARSHAD NUMBER ABOVE 1000 = ,I4*$
END OF PROGRAM </syntaxhighlight>
{{out}}
<pre>FIRST 20 HARSHAD NUMBERS:
HARSHAD( 1) = 1
HARSHAD( 2) = 2
HARSHAD( 3) = 3
HARSHAD( 4) = 4
HARSHAD( 5) = 5
HARSHAD( 6) = 6
HARSHAD( 7) = 7
HARSHAD( 8) = 8
HARSHAD( 9) = 9
HARSHAD(10) = 10
HARSHAD(11) = 12
HARSHAD(12) = 18
HARSHAD(13) = 20
HARSHAD(14) = 21
HARSHAD(15) = 24
HARSHAD(16) = 27
HARSHAD(17) = 30
HARSHAD(18) = 36
HARSHAD(19) = 40
HARSHAD(20) = 42
FIRST HARSHAD NUMBER ABOVE 1000 = 1002</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
Define a testing function whether n is harshad or not
<langsyntaxhighlight MATLABlang="matlab">function v = isharshad(n)
v = isinteger(n) && ~mod(n,sum(num2str(n)-'0'));
end; </langsyntaxhighlight>
Check numbers
<langsyntaxhighlight MATLABlang="matlab">k=1; n=1;
while (k<=20)
if isharshad(n)
Line 2,127 ⟶ 3,151:
n=n+1;
end;
printf('\nFirst harshad number larger than 1000 is %i\n',n);</langsyntaxhighlight>
<pre>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</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that returns a list of digits given a nonnegative integer */
decompose(num) := block([digits, remainder],
digits: [],
while num > 0 do
(remainder: mod(num, 10),
digits: cons(remainder, digits),
num: floor(num/10)),
digits
)$
 
/* Function that returns a list of the first len Harshad numbers */
harshad_count(len):=block(
[i:1,count:0,result:[]],
while count<len do (if map(lambda([x],if mod(x,apply("+",decompose(x)))=0 then true),[i])=[true] then (result:endcons(i,result),count:count+1),i:i+1),
result)$
 
/* Function that returns a list of the Harshad numbers up to len */
first_count(len):=block(
[i:1,count:0,result:[]],
while i<=len do (if map(lambda([x],if mod(x,apply("+",decompose(x)))=0 then true),[i])=[true] then (result:endcons(i,result),count:count+1),i:i+1),
length(result))$
 
/* Test cases */
harshad_count(20);
block(first_count(1000),last(harshad_count(%%+1)));
</syntaxhighlight>
{{out}}
<pre>
[1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
1002
</pre>
 
=={{header|MMBasic}}==
<syntaxhighlight lang="bbcbasic">
number = 1
tally = 0
 
print "First 20 Harshad numbers:"
do while tally < 20
if isHarshad(number) = 0 then
print number;
tally = tally + 1
endif
number = number + 1
loop
 
 
number = 1001
endloop = 0
print ""
 
do
if isHarshad(number) = 0 then
print "The first Harshad number greater than 1000 is"; number
endloop = 1
endif
number = number + 1
loop until endloop = 1
 
function digitSum(x)
let y$ = str$(x)
for i = 1 to len(y$)
digitSum = digitSum + val(mid$(y$,i,1))
next i
end function
 
function isHarshad(num)
isHarshad = num MOD digitSum(num)
end function
 
</syntaxhighlight>
 
{{out}}
<pre>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 first Harshad number greater than 1000 is 1002</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE Harshad;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
 
VAR n, i: CARDINAL;
 
PROCEDURE DigitSum(n: CARDINAL): CARDINAL;
VAR sum: CARDINAL;
BEGIN
sum := 0;
WHILE n > 0 DO;
sum := sum + n MOD 10;
n := n DIV 10;
END;
RETURN sum;
END DigitSum;
 
PROCEDURE NextHarshad(n: CARDINAL): CARDINAL;
BEGIN
REPEAT INC(n);
UNTIL n MOD DigitSum(n) = 0;
RETURN n;
END NextHarshad;
 
BEGIN
n := 0;
WriteString("First 20 Harshad numbers:");
WriteLn();
FOR i := 1 TO 20 DO
n := NextHarshad(n);
WriteCard(n, 3);
END;
WriteLn();
WriteString("First Harshad number above 1000: ");
WriteCard(NextHarshad(1000), 4);
WriteLn();
END Harshad.</syntaxhighlight>
{{out}}
<pre>First 20 Harshad numbers:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First Harshad number above 1000: 1002</pre>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(
:n () =list
(n 0 >) (
Line 2,153 ⟶ 3,299:
 
0 (next-harshad print " " print!) 20 times newline
1000 next-harshad print!</langsyntaxhighlight>
{{out}}
<pre>
Line 2,160 ⟶ 3,306:
</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout ("First 20: " ++ show first20 ++ "\n"),
Stdout ("First above 1000: " ++ show above1000 ++ "\n")]
 
first20 :: [num]
first20 = take 20 (filter isharshad [1..])
 
above1000 :: num
above1000 = hd (filter isharshad [1001..])
 
isharshad :: num->bool
isharshad n = n mod digitsum n = 0
 
digitsum :: num->num
digitsum 0 = 0
digitsum n = n mod 10 + digitsum (n div 10)</syntaxhighlight>
{{out}}
<pre>First 20: [1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
First above 1000: 1002</pre>
=={{header|MLite}}==
<langsyntaxhighlight lang="ocaml">fun sumdigits
(0, n) = n
| (m, n) = sumdigits (m div 10, m rem 10) + n
Line 2,187 ⟶ 3,354:
 
print "first twenty harshad numbers = "; println ` harshad 20;
print "first harshad number after 1000 = "; println ` next_harshad_after 1000;</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/* NetRexx ------------------------------------------------------------
* 21.01.2014 Walter Pachl translated from ooRexx (from REXX version 1)
*--------------------------------------------------------------------*/
Line 2,224 ⟶ 3,391:
sum=sum+n.substr(k,1)
End
Return sum</langsyntaxhighlight>
'''output''' same as ooRexx's
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc slice[T](iter: iterator(): T {.closure.}; sl: Slice[T]): seq[T] =
var i = 0
for n in iter():
Line 2,248 ⟶ 3,415:
if n > 1000:
echo n
break</langsyntaxhighlight>
{{out}}
<pre>@[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
Line 2,254 ⟶ 3,421:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Harshad {
function : Main(args : String[]) ~ Nil {
Line 2,283 ⟶ 3,450:
}
}
</syntaxhighlight>
</lang>
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let is_harshad x =
let rec dsum n = if n < 10 then n else dsum (n / 10) + n mod 10 in
x mod dsum x = 0
 
let () =
let print_seq (x, n) =
Seq.(ints x |> filter is_harshad |> take n |> map string_of_int)
|> List.of_seq |> String.concat ", " |> print_endline
in
List.iter print_seq [1, 20; 1001, 1]</syntaxhighlight>
{{out}}
<pre>
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42
1002
</pre>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: sumDigits(n) 0 while(n) [ n 10 /mod ->n + ] ;
: isHarshad dup sumDigits mod 0 == ;
 
1100 seq filter(#isHarshad) dup left(20) println dup filter(#[ 1000 > ]) first println</langsyntaxhighlight>
 
{{out}}
Line 2,300 ⟶ 3,484:
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* 21.01.2014 Walter Pachl modi-(simpli-)fied from REXX version 1
*--------------------------------------------------------------------*/
Line 2,332 ⟶ 3,516:
sum=sum+substr(n,k,1)
End
Return sum</langsyntaxhighlight>
{{out}}
<pre>first 20 Niven numbers: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
Line 2,339 ⟶ 3,523:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.6.0 and above}}
<langsyntaxhighlight 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)</langsyntaxhighlight>
{{out}}
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42,
Line 2,348 ⟶ 3,532:
=={{header|Pascal}}==
{{works with|Free Pascal}}
{{works with|Delphi}}
 
Optimized for speed, by using the state before in IncSumDigit.
<langsyntaxhighlight lang="pascal">program Niven;
 
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
 
const
base = 10;
 
type
tNum = longword; {Uint64}
{$IFDEF FPC}
 
const
cntbasedigits = trunc(ln(High(tNum)) / ln(base)) + 1;
{$ELSE}
 
var
cntbasedigits: Integer = 0;
{$ENDIF}
 
type
tSumDigit = record
sdNumber : tNum;
{$IFDEF FPC}
sdDigits : array[0..cntbasedigits-1] of byte;
sdDigits: array[0..cntbasedigits - 1] sdSumDig :of byte;
{$ELSE}
sdIsNiven : boolean;
sdDigits: endTArray<Byte>;
{$ENDIF}
sdSumDig: byte;
sdIsNiven: boolean;
end;
 
function InitSumDigit( n : tNum): tSumDigit;
var
sd : tSumDigit;
qt : tNum;
i : integer;
begin
with sd do
begin
sdNumber := n;
{$IFDEF FPC}
fillchar(sdDigits,SizeOf(sdDigits),#0);
fillchar(sdDigits, SizeOf(sdDigits), #0);
sdSumDig :=0;
{$ELSE}
SetLength(sdDigits,cntbasedigits);
fillchar(sdDigits[0], SizeOf(sdDigits), #0);
{$ENDIF}
sdSumDig := 0;
sdIsNiven := false;
i := 0;
Line 2,382 ⟶ 3,591:
qt := n div base;
{n mod base}
sdDigits[i] := n - qt * base;
inc(sdSumDig, sdDigits[i]);
n := qt;
inc(i);
end;
IFif sdSumDig > 0 then
sdIsNiven := (sdNumber MODmod sdSumDig = 0);
end;
InitSumDigit := sd;
end;
 
procedure IncSumDigit(var sd: tSumDigit);
var
i, d: integer;
begin
i := 0;
Line 2,414 ⟶ 3,623:
begin
sdDigits[i] := 0;
dec(sdSumDig, base);
inc(i);
end;
until i > high( sdDigits);
sdIsNiven := (sdNumber MODmod sdSumDig) = 0;
end;
end;
 
var
MySumDig : tSumDigit;
ln lnn: tNum;
cnt: integer;
 
begin
{$IFNDEF FPC}
MySumDig:=InitSumDigit(0);
cntbasedigits := trunc(ln(High(tNum)) / ln(base)) + 1;
{$ENDIF}
 
MySumDig := InitSumDigit(0);
cnt := 0;
repeat
IncSumDigit(MySumDig);
IFif 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;
lnlnn := MySumDig.sdNumber;
repeat
IncSumDigit(MySumDig);
if MySumDig.sdIsNiven then
begin
IFif cnt < (MySumDig.sdNumber -ln lnn) then
begin
cnt := (MySumDig.sdNumber -ln lnn);
writeln(lnlnn, ' --> ', MySumDig.sdNumber, ' d=', cnt);
end;
lnlnn := MySumDig.sdNumber;
end;
until MySumDig.sdNumber = High(tNum);
{
689988915 --> 689989050 d=135
Line 2,466 ⟶ 3,680:
2998895823 --> 2998895976 d=153
~ 24 Cpu-cycles per test i3- 4330 1..2^32-1}
{$IFNDEF LINUX}readln;{$ENDIF}
end.</lang>
end.</syntaxhighlight>
output:
<pre>1.2.3.4.5.6.7.8.9.10.12.18.20.21.24.27.30.36.40.42.....1002.</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use v5.36;
<lang perl>#!/usr/bin/perl
use strictList::Util 'sum';
use warnings ;
use List::Util qw ( sum ) ;
 
sub createHarshads ($limit) {
my (@harshads ,$number);
my $numberdo = 1 ;{
$number++;
do {
if ( $number % sum ( split ( // , $number ) ) == 0 ) {
push @harshads , $number ;
}
} until $number++harshads[ -1 ] > $limit;
} untilreturn ( $@harshads[ -1 ] > 1000 ) ;
return @harshads ;
}
 
my @harshadnumbers = createHarshads ;
my @harshadnumbers = createHarshads my $limit = 1000;
for my $i ( 0..19 ) {
printsay "$@harshadnumbers[ $i 0..19]\n" ;
say "The first Harshad number greater than $limit is $harshadnumbers[ -1 ]!" ;</syntaxhighlight>
}
print "The first Harshad number greater than 1000 is $harshadnumbers[ -1 ]!\n" ;</lang>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
<pre>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!</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
<lang Phix>integer n = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
sequence digits={0}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">digits</span><span style="color: #0000FF;">={</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span>
 
procedure nNiven()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">nNiven</span><span style="color: #0000FF;">()</span>
while 1 do
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
n += 1
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
for i=length(digits) to 0 by -1 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">to</span> <span style="color: #000000;">0</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
if i=0 then
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
digits = prepend(digits,1)
<span style="color: #000000;">digits</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
exit
end if <span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if digits[i]<9 then
<span style="color: #008080;">if</span> <span style="color: #000000;">digits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]<</span><span style="color: #000000;">9</span> <span style="color: #008080;">then</span>
digits[i] += 1
<span style="color: #000000;">digits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
exit
end if <span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
digits[i] = 0
<span style="color: #000000;">digits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if remainder(n,sum(digits))=0 then exit end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
sequence s = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
for i=1 to 20 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
nNiven()
<span style="color: #000000;">nNiven</span><span style="color: #0000FF;">()</span>
s &= n
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
?s
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
while n<=1000 do
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">1000</span> <span style="color: #008080;">do</span>
nNiven()
<span style="color: #000000;">nNiven</span><span style="color: #0000FF;">()</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
?n</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">n</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,553 ⟶ 3,747:
</pre>
Alternative version
<!--<syntaxhighlight lang="phix">-->
<lang Phix>function isHarshad(integer n)
<span style="color: #008080;">function</span> <span style="color: #000000;">isHarshad</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
return remainder(n,sum(sq_sub(sprint(n),'0')))=0
<span style="color: #008080;">return</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)))=</span><span style="color: #000000;">0</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
sequence s = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
integer n = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
while length(s)<20 do
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
n += 1
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if isHarshad(n) then
<span style="color: #008080;">if</span> <span style="color: #000000;">isHarshad</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
s &= n
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
n = 1001
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1001</span>
while not isHarshad(n) do n += 1 end while
<span style="color: #008080;">while</span> <span style="color: #008080;">not</span> <span style="color: #000000;">isHarshad</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
?s&n</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">&</span><span style="color: #000000;">n</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,574 ⟶ 3,770:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
#if niven number, return it.
(de niven (N)
Line 2,590 ⟶ 3,786:
(printsp ~(list ~(head 20
(nivGen 1 1000) ) (max ~(nivGen 1001 1010)) ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002
</pre>
 
=={{header|PILOT}}==
<syntaxhighlight lang="pilot">C :n=0
:i=0
*first20
U :*harshad
C :i=i+1
T :#i: #n
J (i<20):*first20
C :n=1000
U :*harshad
T :First Harshad number greater than 1000: #n
E :
*harshad
C :n=n+1
:r=n
:s=0
*digit
C :a=r/10
:s=s+(r-a*10)
:r=a
J (r):*digit
J (n<>s*(n/s)):*harshad
E :</syntaxhighlight>
{{out}}
<pre>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
First Harshad number greater than 1000: 1002</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source or(!) xref attributes;
niven: Proc Options(main);
/*********************************************************************
Line 2,648 ⟶ 3,890:
End;
 
End;</langsyntaxhighlight>
 
{{out}}
<pre>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</pre>
 
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
 
/* FIND THE SUM OF THE DIGITS OF A 16-BIT NUMBER */
DIGIT$SUM: PROCEDURE(N) BYTE;
DECLARE N ADDRESS, SUM BYTE;
SUM = 0;
DO WHILE N > 0;
SUM = SUM + (N MOD 10);
N = N / 10;
END;
RETURN SUM;
END DIGIT$SUM;
 
/* FIND THE NEXT HARSHAD NUMBER ABOVE N */
NEXT$HARSHAD: PROCEDURE(N) ADDRESS;
DECLARE N ADDRESS;
NEXT:
N = N + 1;
IF N MOD DIGIT$SUM(N) = 0 THEN
RETURN N;
ELSE
GO TO NEXT;
END NEXT$HARSHAD;
 
/* CP/M SYSCALL */
BDOS: PROCEDURE(FUNC, ARG);
DECLARE FUNC BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
 
/* PRINT A STRING */
PRINT$STRING: PROCEDURE(STRING);
DECLARE STRING ADDRESS;
CALL BDOS(9, STRING);
END PRINT$STRING;
 
/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE(N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, (C BASED P) BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = (N MOD 10) + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT$STRING(P);
END PRINT$NUMBER;
 
DECLARE CRLF DATA (13,10,'$');
DECLARE N ADDRESS INITIAL (0), S BYTE;
 
/* PRINT FIRST 20 HARSHADS */
CALL PRINT$STRING(.'FIRST 20: $');
DO S = 1 TO 20;
CALL PRINT$NUMBER(N := NEXT$HARSHAD(N));
END;
CALL PRINT$STRING(.CRLF);
 
/* PRINT HARSHAD NUMBER ABOVE 1000 */
CALL PRINT$STRING(.'FIRST ABOVE 1000: $');
CALL PRINT$NUMBER(NEXT$HARSHAD(1000));
CALL PRINT$STRING(.CRLF);
 
CALL BDOS(0,0);
EOF</syntaxhighlight>
{{out}}
<pre>FIRST 20: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
FIRST ABOVE 1000: 1002</pre>
 
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
In PowerShell, we generally don't wrap every little thing in a function. If you have something simple to do, you just do it.
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..1000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 20
1001..2000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 1
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,686 ⟶ 3,999:
</pre>
But if we do have a need for the code to be reusable, we can do that.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-HarshadNumbers
{
Line 2,728 ⟶ 4,041:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-HarshadNumbers -Count 20
Get-HarshadNumbers -Minimum 1001 -Count 1
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,760 ⟶ 4,073:
=={{header|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.
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(lambda)).
 
niven :-
Line 2,802 ⟶ 4,115:
sum_list(LN, S).
 
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- niven.
Line 2,828 ⟶ 4,141:
 
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">If OpenConsole()=0 : End 1 : EndIf
 
Procedure.i Niven(v.i)
w=v
While v : s+v%10 : v/10 : Wend
If w%s=0 : ProcedureReturn w : EndIf
EndProcedure
 
Repeat
i+1
If Niven(i) : c+1 : Print(Str(i)+" ") : EndIf
If c=20 And i<1000 : Print("... ") : i=1000 : EndIf
If c=21 : Break : EndIf
ForEver
 
Input()</syntaxhighlight>
{{out}}<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002 </pre>
 
=={{header|Python}}==
===Python: Procedural===
<langsyntaxhighlight lang="python">>>> import itertools
>>> def harshad():
for n in itertools.count(1):
Line 2,847 ⟶ 4,179:
1002
>>> </langsyntaxhighlight>
 
===Python: Functional===
The for loop above [http://paddy3118.blogspot.co.uk/2013/03/itertoolsfirst.html 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:
<langsyntaxhighlight 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))
Line 2,857 ⟶ 4,189:
>>> next(x for x in harshad if x > 1000)
1002
>>> </langsyntaxhighlight>
 
And we cancould also sum digits more directly (without string coercion) while still preserving functional composition:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Harshad or Niven series'''
 
from itertools import chain, count, dropwhile, islice
 
 
Line 2,870 ⟶ 4,202:
def harshads():
'''Harshad series'''
defreturn go(x):
return [x] iffor 0 == (x %in digitSumcount(x1)) else []
if 0 == x % digitSum(x)
return chain.from_iterable(
map(go, count(1))
)
 
Line 2,881 ⟶ 4,212:
'''Sum of the decimal digits of n.'''
def go(x):
return Nothing()None if 0 == x else Just(divmod(x, 10))
return sum(unfoldl(go)(n))
 
 
# TEST --------------------------- TEST -------------------------
# main :: IO ()
def main():
Line 2,908 ⟶ 4,239:
 
 
# GENERIC ------------------------- GENERIC ------------------------
 
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
 
 
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
 
 
# take :: Int -> [a] -> [a]
Line 2,939 ⟶ 4,254:
 
 
# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)
# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
def unfoldl(f):
'''A lazy (generator) list unfolded from a seed value
'''Dual to reduce or foldl.
Whereby theserepeated reduceapplication aof listf tountil ano summaryresidue value, unfoldlremains.
buildsDual ato list from a seed valuefold/reduce.
Where f returns Just(a,either b),None aor isjust appended(residue, to the list,value).
andFor thea residualstrict boutput islist, used aswrap the argumentresult for thewith nextlist()
application of f.
When f returns Nothing, the completed list is returned.
'''
def go(v):
x, rresidueValue = f(v, v)
xswhile = []residueValue:
while True: yield residueValue[1]
mbresidueValue = f(xresidueValue[0])
return go
if mb.get('Nothing'):
return xs
else:
x, r = mb.get('Just')
xs.insert(0, r)
return xs
return lambda x: go(x)
 
 
# DISPLAY ------------------------- DISPLAY ------------------------
 
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
fx display function -> f -> xs -> tabular string.
'''
def gogox(xShow, fxShow, f, xs):
ysdef = [xShowgofx(xfxShow) for x in xs]:
w = max(map(len, ys) def gof(f):
return s + '\n' + '\n'.join(map def goxs(xs):
lambda x, y: y.rjust(w, ' ') + ' ->ys '= + fxShow(f[xShow(x)), for x in xs]
xs w = max(map(len, ys))
 
))
def arrowed(x, y):
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
return y.rjust(w, ' ') + ' -> ' + (
xShow, fxShow, f, xs
fxShow(f(x))
)
)
return s + '\n' + '\n'.join(
map(arrowed, xs, ys)
)
return goxs
return gof
return gofx
return gox
 
 
Line 2,993 ⟶ 4,306:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Harshad or Niven series:
Line 2,999 ⟶ 4,312:
firstTwenty -> [1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,36,40,42]
firstAbove1000 -> [1002]</pre>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">[ number$ $ "0 " swap
witheach
[ join $ " + " join ]
quackery ] is digitsum ( n --> n )
 
[ dup digitsum
mod 0 = ] is isharshad ( n --> b )
 
say "The first 20 Harshad numbers are: "
0 1
[ dup isharshad if
[ dup echo sp dip 1+ ]
1+
over 20 = until ]
2drop
cr
cr
say "The first Harshad number greater than 1000 is: "
1000 [ 1+ dup isharshad
iff echo done
again ]
cr
</syntaxhighlight>
'''Output:'''
<pre>The first 20 Harshad numbers are: 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
 
</pre>
 
 
=={{header|Racket}}==
<langsyntaxhighlight lang="scheme">#lang racket
 
(define (digsum n)
Line 3,013 ⟶ 4,360:
; First harshad greater than 1000
(displayln (for/first ([h harshads] #:when(> h 1000)) h))</langsyntaxhighlight>
 
{{out}}
Line 3,021 ⟶ 4,368:
Different to the Scheme implementation in that it illustrates Racket's native iterators,
and ''let-values'' with ''quotient/remainder'':
<langsyntaxhighlight lang="racket">#lang racket
(require math/number-theory)
(define (digital-sum n)
Line 3,040 ⟶ 4,387:
 
;; find 1st Harshad number > 1000
(displayln (for/first ((h (sequence-filter harshad-number? (in-naturals 1001)))) h))</langsyntaxhighlight>
{{out}}
<pre>#1 1
Line 3,068 ⟶ 4,415:
 
{{works with|Rakudo|2016.08}}
<syntaxhighlight lang="raku" perl6line>constant @harshad = grep { $_ %% .comb.sum }, 1 .. *;
say @harshad[^20];
say @harshad.first: * > 1000;</langsyntaxhighlight>
{{out}}
<pre>(1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42)
1002</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout 'First 20: ' <GetFirst 20 Harshad>>
<Prout 'First > 1000: ' <Next Harshad 1000>>;
};
 
GetFirst {
s.N s.F = <GetFirst s.N s.F 0>;
0 s.F s.Cur = ;
s.N s.F s.Cur, <Next s.F s.Cur>: s.Next
= s.Next <GetFirst <- s.N 1> s.F s.Next>;
};
 
Next {
s.F s.N, <+ 1 s.N>: s.Next, <Mu s.F s.Next>: {
T = s.Next;
F = <Next s.F s.Next>;
};
};
 
Harshad {
s.N, <DigSum s.N>: s.Dsum, <Mod s.N s.Dsum>: 0 = T;
s.N = F;
};
 
DigSum {
0 = 0;
s.N, <Divmod s.N 10>: (s.Rest) s.Dgt = <+ s.Dgt <DigSum s.Rest>>;
};</syntaxhighlight>
{{out}}
<pre>First 20: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First > 1000: 1002</pre>
 
=={{header|REXX}}==
Line 3,082 ⟶ 4,462:
Also, gihugeic integers are supported &nbsp; (essentially no limit).
===generic===
<langsyntaxhighlight lang="rexx">/*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/
parse arg A B . /*obtain optional arguments from the CL*/
if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/
Line 3,097 ⟶ 4,477:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDigs: parse arg x 1 s 2 q; do k=1 for length(q); s= s+substr(q,k,1); end; return s</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,106 ⟶ 4,486:
===idiomatic===
This REXX version idiomatically uses a &nbsp; '''isNiven''' &nbsp; function.
<langsyntaxhighlight lang="rexx">/*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/
parse arg A B . /*obtain optional arguments from the CL*/
if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/
Line 3,122 ⟶ 4,502:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isNiven: parse arg x 1 s 2 q; do k=1 for length(q); s=s+substr(q,k,1); end; return x//s==0</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
Line 3,128 ⟶ 4,508:
This REXX version optimizes the &nbsp; '''isNiven''' &nbsp; function by using &nbsp; '''parse''' &nbsp; statements instead of the &nbsp; '''substr''' &nbsp; BIF,
<br>yielding a faster algorithm.
<langsyntaxhighlight lang="rexx">/*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/
parse arg A B . /*obtain optional arguments from the CL*/
if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/
Line 3,147 ⟶ 4,527:
do length(q); parse var q _ 2 q; sum= sum + _
end /*length(q)*/ /* ↑ */
return x // sum == 0 /* └──────◄ is destructively parsed. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
Line 3,154 ⟶ 4,534:
 
In addition, if the &nbsp; '''A''' &nbsp; number is negative, the numbers in the array aren't displayed, but the &nbsp; ''last'' &nbsp; number in the array is displayed.
<langsyntaxhighlight lang="rexx">/*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/
parse arg A B . /*obtain optional arguments from the CL*/
if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/
Line 3,179 ⟶ 4,559:
do while q\==''; parse var q _ 2 q; sum= sum + _
end /*while*/ /* ↑ */
return x // sum == 0 /* └──────◄ is destructively parsed.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when the input used is: &nbsp; &nbsp; <tt> -1000000 &nbsp; 66777888 </tt>}}
<pre>
Line 3,188 ⟶ 4,568:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
i = 1
count = 0
Line 3,206 ⟶ 4,586:
niv = ((nr % sum) = 0)
return niv
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,230 ⟶ 4,610:
42 is a Niven number
1002 is a Niven number
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code
! Comments
|-
|
≪ '''DO'''
1 + DUP DUP →STR DUP SIZE → n len
≪ 0 1 len '''FOR''' j
n j DUP SUB NUM +
'''NEXT'''
len 48 * -
'''UNTIL''' MOD NOT '''END'''
'NXTHR' STO
≪ {} 0
1 20 '''START''' NXTHR SWAP OVER + SWAP '''NEXT''' DROP
1000 NXTHR
≫ EVAL
|
''( n -- next_Harshad_number)''
Increment n and initialize local variables
Add ASCII codes
Remove offset 48 = NUM("0")
Create list of first 20 Harshad numbers
Get first Harshad number > 1000
|}
{{out}}
<pre>
2: { 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 }
1: 1002
</pre>
 
Line 3,235 ⟶ 4,660:
{{works with|Ruby|2.4}}
Ruby 2.4 gave Integers a '''digits''' method, and Arrays a '''sum''' method.
<langsyntaxhighlight Rubylang="ruby">harshad = 1.step.lazy.select { |n| n % n.digits.sum == 0 }
 
puts "The first 20 harshard numbers are: \n#{ harshad.first(20) }"
puts "The first harshard number > 1000 is #{ harshad.find { |n| n > 1000 } }"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,248 ⟶ 4,673:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">while count < 20
h = h + 1
if neven(h) = 0 then
Line 3,271 ⟶ 4,696:
next i
neven = h mod d
end function</langsyntaxhighlight>
{{out}}
<pre>
Line 3,298 ⟶ 4,723:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
<lang Rust>
fn is_hashardis_harshad (n : u32) -> bool {
let sum_digits = n.to_string()
.chars()
Line 3,308 ⟶ 4,733:
 
fn main() {
for i in (1u32..).filter(|num| is_hashardis_harshad(*num)).take(20) {
println!("HashardHarshad : {}", i);
}
for i in (1_001u32..).filter(|num| is_hashardis_harshad(*num)).take(1) {
println!("First HashardHarshad bigger than 1_000 : {}", i);
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
HashardHarshad : 1
HashardHarshad : 2
HashardHarshad : 3
HashardHarshad : 4
HashardHarshad : 5
HashardHarshad : 6
HashardHarshad : 7
HashardHarshad : 8
HashardHarshad : 9
HashardHarshad : 10
HashardHarshad : 12
HashardHarshad : 18
HashardHarshad : 20
HashardHarshad : 21
HashardHarshad : 24
HashardHarshad : 27
HashardHarshad : 30
HashardHarshad : 36
HashardHarshad : 40
HashardHarshad : 42
First HashardHarshad bigger than 1_000 : 1002
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object Harshad extends App {
val harshads = Stream.from(1).filter(i => i % i.toString.map(_.asDigit).sum == 0)
 
val harshads = Stream from 1 filter (i => i % i.toString.map(_.asDigit).sum == 0)
 
println(harshads.take(20).toList)
println(harshads.filter(_ > 1000).head)
}</syntaxhighlight>
 
}</lang>
{{out}}
<pre>List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42)
Line 3,356 ⟶ 4,779:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">#!/usr/local/bin/gosh
 
;; Show the first 20 niven numbers and the
Line 3,381 ⟶ 4,804:
(apply + (map string->number (map string (string->list (number->string n))))))
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,390 ⟶ 4,813:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: sumOfDigits (in var integer: num) is func
Line 3,423 ⟶ 4,846:
current := 1001;
writeln(" ... " <& nextHarshadNum(current));
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,429 ⟶ 4,852:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 ... 1002
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program harshad;
print("First 20 Harshad numbers:", [n := next(n) : i in [1..20]]);
print("First Harshad number >1000:", next(1000));
 
proc next(n);
(until harshad(n)) n +:= 1; end;
return n;
end proc;
 
proc harshad(n);
return n mod +/[val d : d in str n] = 0;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>First 20 Harshad numbers: [1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42]
First Harshad number >1000: 1002</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func harshad() {
var n = 0;
{
++n while !(n %% n.digits.sum.divides(n);
n;
}
}
 
var iter = harshad();
say 20.of { iter.run };
 
var n;
do {
n = iter.run
} while (n <= 1000);
 
say n;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,456 ⟶ 4,897:
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM. <code>FAST</code> isn't all that fast.
<langsyntaxhighlight lang="basic"> 10 FAST
20 LET N=0
30 LET H=0
Line 3,470 ⟶ 4,911:
130 IF N>1000 THEN GOTO 150
140 GOTO 40
150 SLOW</langsyntaxhighlight>
{{out}}
<pre>1
Line 3,496 ⟶ 4,937:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">struct Harshad: Sequence, IteratorProtocol {
private var i = 0
 
Line 3,511 ⟶ 4,952:
 
print("First 20: \(Array(Harshad().prefix(20)))")
print("First over a 1000: \(Harshad().first(where: { $0 > 1000 })!)")</langsyntaxhighlight>
 
{{out}}
Line 3,519 ⟶ 4,960:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># Determine if the given number is a member of the class of Harshad numbers
proc isHarshad {n} {
if {$n < 1} {return false}
Line 3,536 ⟶ 4,977:
# Get the first value greater than 1000 that satisfies the condition
for {set n 1000} {![isHarshad [incr n]]} {} {}
puts "First Harshad > 1000 = $n"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,544 ⟶ 4,985:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">C=0
 
For I = 1 Step 1 Until C = 20 ' First 20 Harshad numbers
Line 3,566 ⟶ 5,007:
Loop
 
Return ((a@ % b@) = 0)</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002
 
0 OK, 0:185</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
<syntaxhighlight lang="bash">function main {
local -i i=0 n
gen_harshad | while read n; do
if (( !i )); then
printf '%d' "$n"
elif (( i < 20 )); then
printf ' %d' "$n"
elif (( i == 20 )); then
printf '\n'
elif (( n > 1000 )); then
printf '%d\n' "$n"
return
fi
(( i++ ))
done
}
 
function is_harshad {
local -i sum=0 n=$1 i
for (( i=0; i<${#n}; ++i )); do
(( sum += ${n:$i:1} ))
done
(( n % sum == 0 ))
}
 
function gen_harshad {
local -i i=1
while true; do
if is_harshad $i; then
printf '%d\n' "$i"
fi
(( i++ ))
done
}
 
main "$@"</syntaxhighlight>
{{Out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002
</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 3,597 ⟶ 5,083:
Next i
IsHarshad = sNumber Mod Summ = 0
End Function</langsyntaxhighlight>
 
{{out}}
Line 3,605 ⟶ 5,091:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">n = 0
m = 1
first20 = ""
Line 3,640 ⟶ 5,126:
IsHarshad = True
End If
End Function</langsyntaxhighlight>
 
{{out}}
Line 3,649 ⟶ 5,135:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
LOCAL lnCount As Integer, k As Integer
CLEAR
Line 3,679 ⟶ 5,165:
RETURN n % d = 0
ENDFUNC
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,705 ⟶ 5,191:
First such number > 1000: 1002
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
fn main() {
mut count, mut i := 0, 0
print("The first 20 Harshad numbers: ")
for {
i++
if is_harshad(i) == true {
if count < 20 {print("${i} ") count++}
if i > 1000 {print("\nThe first Harshad number above 1000: ${i}") break}
}
}
}
 
fn sum_digits(number int) int {
mut num, mut sum := number, 0
if number <= 0 {return 0}
for num > 0 {
sum += num % 10
num /= 10
}
return sum
}
 
fn is_harshad(n int) bool {
if n % sum_digits(n) == 0 {return true}
return false
}
</syntaxhighlight>
 
{{out}}
<pre>
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 first Harshad number above 1000: 1002
</pre>
 
=={{header|VTL-2}}==
<syntaxhighlight lang="vtl2">10 ?="First 20: ";
20 N=0
30 I=0
40 #=200
50 ?=N
60 $=32
70 I=I+1
80 #=I<20*40
90 ?=""
100 ?="First above 1000: ";
110 N=1000
120 #=200
130 ?=N
140 #=999
200 ;=!
210 N=N+1
220 K=N
230 S=0
240 K=K/10
250 S=S+%
260 #=0<K*240
270 #=N/S*0+0<%*210
280 #=;</syntaxhighlight>
{{out}}
<pre>First 20: 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
First above 1000: 1002</pre>
 
=={{header|Whitespace}}==
<syntaxhighlight lang="whitespace">
<lang Whitespace>
Line 3,769 ⟶ 5,319:
 
</syntaxhighlight>
</lang>
This solution was generated from the pseudo-Assembly below.
A [http://ideone.com/AKxEMY live run] is available for the inquiring skeptic.
<langsyntaxhighlight lang="asm">push 0 ; Harshad numbers found
push 0 ; counter
 
Line 3,797 ⟶ 5,347:
 
3: ; Print the > 1000 Harshad number on its own line and exit clean.
push 10 ochr onum pop push 10 ochr exit</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
Line 3,803 ⟶ 5,353:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var niven = Fiber.new {
var n = 1
while (true) {
Line 3,828 ⟶ 5,378:
break
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,839 ⟶ 5,389:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int H, C, N, S; \Harshad number, Counter, Number, Sum
[H:= 1; C:= 0;
Line 3,852 ⟶ 5,402:
H:= H+1;
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,858 ⟶ 5,408:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002
</pre>
 
 
=={{header|Yabasic}}==
{{trans|BASIC256}}
<syntaxhighlight lang="yabasic">
sub sumDigits(n)
if n < 0 then return 0 : endif
local sum
while n > 0
sum = sum + mod(n, 10)
n = int(n / 10)
wend
return sum
end sub
 
sub isHarshad(n)
return mod(n, sumDigits(n)) = 0
end sub
 
print "Los primeros 20 numeros de Harshad o Niven son:"
contar = 0
i = 1
 
repeat
if isHarshad(i) then
print i, " ",
contar = contar + 1
end if
i = i + 1
until contar = 20
 
print : print
print "El primero de esos numeros por encima de 1000 es:"
i = 1001
 
do
if isHarshad(i) then
print i, " "
break
end if
i = i + 1
loop
print
end
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de BASIC256.
</pre>
 
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn harshad(n){ 0==n%(n.split().sum(0)) }
[1..].tweak(fcn(n){ if(not harshad(n)) return(Void.Skip); n })
.walk(20).println();
[1..].filter(20,harshad).println();
[1001..].filter1(harshad).println();</langsyntaxhighlight>
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.
 
Line 3,877 ⟶ 5,477:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<langsyntaxhighlight lang="zxbasic">10 LET k=0: LET n=0
20 IF k=20 THEN GO TO 60
30 LET n=n+1: GO SUB 1000
Line 3,893 ⟶ 5,493:
1050 LET isHarshad=NOT FN m(n,s)
1060 RETURN
1100 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
2,125

edits