Sum digits of an integer: Difference between revisions

m
Missing "4" in "1234"
m (Missing "4" in "1234")
 
(47 intermediate revisions by 21 users not shown)
Line 11:
=={{header|11l}}==
{{trans|Nim}}
<syntaxhighlight lang="11l">F sum_digits(=n, base)
 
<lang 11l>F sum_digits(=n, base)
V r = 0
L n > 0
Line 22 ⟶ 21:
print(sum_digits(1234, 10))
print(sum_digits(F'E, 16))
print(sum_digits(0F'0E, 16))</langsyntaxhighlight>
 
{{out}}
Line 35 ⟶ 34:
{{trans|REXX}}
The program uses two ASSIST macro (XDECO,XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Sum digits of an integer 08/07/2016
SUMDIGIN CSECT
USING SUMDIGIN,R13 base register
Line 90 ⟶ 89:
XDEC DS CL12 temp
YREGS
END SUMDIGIN</langsyntaxhighlight>
{{out}}
<pre>
Line 100 ⟶ 99:
 
=={{header|8086 Assembly}}==
<langsyntaxhighlight lang="asm"> cpu 8086
org 100h
section .text
Line 148 ⟶ 147:
dw 16, 0FEh
dw 16, 0F0Eh
dw 0 ; End marker</langsyntaxhighlight>
 
{{out}}
Line 157 ⟶ 156:
29</pre>
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">CARD FUNC SumDigits(CARD num,base)
CARD res,a
 
Line 182 ⟶ 181:
PrintF("num=%U base=%U sum=%U%E",num,base,res)
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_digits_of_an_integer.png Screenshot from Atari 8-bit computer]
Line 201 ⟶ 200:
Digits is a base-B number. E.g., 30, 10#30# 2#11110#, and 16#1E# are the same number -- either written in decimal, binary or hexadecimal notation.
 
<langsyntaxhighlight Adalang="ada">with Ada.Integer_Text_IO;
 
procedure Sum_Digits is
Line 228 ⟶ 227:
Put(Sum_OF_Digits(16#fe#, 16)); -- 29
Put(Sum_OF_Digits(16#f0e#, 16)); -- 29
end Sum_Digits;</langsyntaxhighlight>
 
{{out}}
Line 236 ⟶ 235:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68">
# operator to return the sum of the digits of an integer value in the #
# specified base #
Line 282 ⟶ 281:
 
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 295 ⟶ 294:
 
==AppleScript==
<langsyntaxhighlight AppleScriptlang="applescript">----------------- SUM DIGITS OF AN INTEGER -----------------
 
-- baseDigitSum :: Int -> Int -> Int
Line 490 ⟶ 489:
end tell
return xs
end unfoldl</langsyntaxhighlight>
{{Out}}
<pre>{{8, 17, 12, 30}, {1, 10}, {29, 29}}</pre>
 
=={{header|APL}}==
<syntaxhighlight lang APL="apl">sd←+/⊥⍣¯1</langsyntaxhighlight>
{{out}}
<pre>
Line 505 ⟶ 504:
 
=={{header|ArnoldC}}==
<langsyntaxhighlight lang="arnoldc">LISTEN TO ME VERY CAREFULLY sumDigits
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE base
Line 541 ⟶ 540:
TALK TO THE HAND "sumDigits 254 16 ="
TALK TO THE HAND sum
YOU HAVE BEEN TERMINATED</langsyntaxhighlight>
{{out}}
<pre>
Line 552 ⟶ 551:
=={{header|Arturo}}==
{{trans|Nim}}
<langsyntaxhighlight lang="rebol">sumDigits: function [n base][
result: 0
while [n>0][
Line 565 ⟶ 564:
print sumDigits 123045 10
print sumDigits from.hex "0xfe" 16
print sumDigits from.hex "0xf0e" 16</langsyntaxhighlight>
 
{{out}}
Line 576 ⟶ 575:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 631 ⟶ 630:
//
} (* end of [main0] *)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 645 ⟶ 644:
''Translated from the C version.''
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % sprintf("%d %d %d %d %d`n"
,SumDigits(1, 10)
,SumDigits(12345, 10)
Line 666 ⟶ 665:
StringReplace,s,s,`%d, % f
return s
}</langsyntaxhighlight>
{{out}}
<pre>1 15 15 29 29</pre>
Line 679 ⟶ 678:
Other versions of AWK may not have these limitations.
 
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 702 ⟶ 701:
return index("0123456789abcdef", tolower(dig)) - 1
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 719 ⟶ 718:
Note that in order for this to work with the Windows versions of PowerBASIC, the test code (the block at the end containing the PRINT lines) needs to be inside <code>FUNCTION PBMAIN</code>.
 
<langsyntaxhighlight lang="qbasic">FUNCTION sumDigits(num AS STRING, bas AS LONG) AS LONG
'can handle up to base 36
DIM outp AS LONG
Line 742 ⟶ 741:
PRINT sumDigits(LTRIM$(STR$(&HFE)), 16)
PRINT sumDigits(LTRIM$(STR$(&HF0E)), 16)
PRINT sumDigits("2", 2)</langsyntaxhighlight>
 
{{out}}
Line 755 ⟶ 754:
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 BASE = 10
20 N$ = "1" : GOSUB 100 : PRINT N
30 N$ = "1234" : GOSUB 100 : PRINT N
Line 772 ⟶ 771:
170 N = N + J - 1
180 NEXT I
190 RETURN</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<langsyntaxhighlight BASIC256lang="basic256">function SumDigits(number, nBase)
if number < 0 then number = -number
if nBase < 2 then nBase = 2
Line 792 ⟶ 791:
print "fe base 16 : "; SumDigits(0xfe, 16)
print "f0e base 16 : "; SumDigits(0xf0e, 16)
end</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
This solution deliberately avoids MOD and DIV so it is not restricted to 32-bit integers.
<syntaxhighlight lang="bbcbasic"> *FLOAT64
PRINT "Digit sum of 1 (base 10) is "; FNdigitsum(1, 10)
PRINT "Digit sum of 12345 (base 10) is "; FNdigitsum(12345, 10)
PRINT "Digit sum of 9876543210 (base 10) is "; FNdigitsum(9876543210, 10)
PRINT "Digit sum of FE (base 16) is "; ~FNdigitsum(&FE, 16) " (base 16)"
PRINT "Digit sum of F0E (base 16) is "; ~FNdigitsum(&F0E, 16) " (base 16)"
END
DEF FNdigitsum(n, b)
LOCAL q, s
WHILE n <> 0
q = INT(n / b)
s += n - q * b
n = q
ENDWHILE
= s</syntaxhighlight>
{{out}}
<pre>
Digit sum of 1 (base 10) is 1
Digit sum of 12345 (base 10) is 15
Digit sum of 9876543210 (base 10) is 45
Digit sum of FE (base 16) is 1D (base 16)
Digit sum of F0E (base 16) is 1D (base 16)
</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">10 rem Sum digits of an integer
20 cls
30 print "The sums of the digits are:"
40 print
50 gosub 100 : print "1 base 10 : " sumdigits(1,10)
60 gosub 100 : print "1234 base 10 : ";sumdigits(1234,10)
70 gosub 100 : print "fe base 16 : " sumdigits(254,16)
80 gosub 100 : print "f0e base 16 : ";sumdigits(3854,16)
90 end
100 sub sumdigits(number,nbase)
110 if number < 0 then number = -number
120 if nbase < 2 then nbase = 2
130 sum = 0
140 while number > 0
150 sum = sum+(number-int(number/nbase)*nbase)
160 number = int(number/nbase)
170 wend
180 sumdigits = sum
190 return</syntaxhighlight><syntaxhighlight lang="scheme">
(define dsum (lambda (x base)
(let ((number (if (string? x) (string->number x base) x)))
(if (= (string-length (number->string number)) 1) number
(+ (mod number base) (dsum (div number base) base))))))
> (dsum 123 10)
6
> (dsum "fe" 16)
29
> (dsum "f0e" 16)
29
> (dsum 1234 10)
10
 
</syntaxhighlight>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">define number = 0, base = 0, sum = 0
 
input "number: ", number
input "base: ", base
 
if number < 0 then
 
let number = number * -1
 
endif
 
if base < 2 then
 
let base = 2
 
endif
 
do
 
if number > 0 then
 
let sum = sum + number % base
let number = int(number / base)
 
endif
 
loop number > 0
 
print "sum of digits in base ", base, ": ", sum
 
end</syntaxhighlight>
{{out| Output}}<pre>
number: 1234567
base: 10
sum of digits in base 10: 28
</pre>
 
==={{header|FreeBASIC}}===
{{trans|PureBasic}}
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function SumDigits(number As Integer, nBase As Integer) As Integer
If number < 0 Then number = -number ' convert negative numbers to positive
If nBase < 2 Then nBase = 2 ' nBase can't be less than 2
Dim As Integer sum = 0
While number > 0
sum += number Mod nBase
number \= nBase
Wend
Return sum
End Function
Print "The sums of the digits are:"
Print
Print "1 base 10 :"; SumDigits(1, 10)
Print "1234 base 10 :"; SumDigits(1234, 10)
Print "fe base 16 :"; SumDigits(&Hfe, 16)
Print "f0e base 16 :"; SumDigits(&Hf0e, 16)
Print
Print "Press any key to quit the program"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
The sums of the digits are:
 
1 base 10 : 1
1234 base 10 : 10
fe base 16 : 29
f0e base 16 : 29
</pre>
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Print "The sums of the digits are:\n"
Print "1 base 10 : "; SumDigits(1, 10)
Print "1234 base 10 : "; SumDigits(1234, 10)
Print "fe base 16 : "; SumDigits(&Hfe, 16)
Print "f0e base 16 : "; SumDigits(&Hf0e, 16)
 
End
 
Function SumDigits(number As Integer, nBase As Integer) As Integer
 
If number < 0 Then number = -number ' convert negative numbers to positive
If nBase < 2 Then nBase = 2 ' nBase can't be less than 2
Dim sum As Integer = 0
While number > 0
sum += number Mod nBase
number \= nBase
Wend
Return sum
 
End Function </syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{trans|Applesoft BASIC}}
<syntaxhighlight lang="qbasic">10 REM Sum digits of an integer
20 CLS : REM 20 HOME for Applesoft BASIC
30 BASE = 10
40 N$ = "1" : GOSUB 100 : PRINT "1 base 10 : " N
50 N$ = "1234" : GOSUB 100 : PRINT "1234 base 10 : " N
60 BASE = 16
70 N$ = "FE" : GOSUB 100 : PRINT "FE base 16 : " N
80 N$ = "F0E" : GOSUB 100 : PRINT "F0E base 16 : " N
90 END
100 REM SUM DIGITS OF N$, BASE
110 IF BASE = 1 THEN N = LEN(N$) : RETURN
120 IF BASE < 2 THEN BASE = 10
130 N = 0 : V$ = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", BASE)
140 FOR I = 1 TO LEN(N$) : C$ = MID$(N$, I, 1)
150 FOR J = 1 TO LEN(V$)
160 IF C$ <> MID$(V$, J, 1) THEN NEXT J : N = SQR(-1) : STOP
170 N = N + J - 1
180 NEXT I
190 RETURN</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{trans|Tiny BASIC}}
Only base ten is supported. Minimal BASIC does not support operations on strings (except assignment to variables).
<langsyntaxhighlight lang="gwbasic">
10 REM Sum digits of an integer
20 PRINT "Enter a number";
Line 809 ⟶ 998:
100 PRINT "Its digit sum:"; S
110 END
</syntaxhighlight>
</lang>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">10 CLS
20 PRINT "The sums of the digits are:" : PRINT
30 B = 10
40 N$ = "1" : GOSUB 100 : PRINT "1 base 10 :" N
50 N$ = "1234" : GOSUB 100 : PRINT "1234 base 10 :" N
60 B = 16
70 N$ = "FE" : GOSUB 100 : PRINT "FE base 16 :" N
80 N$ = "F0E" : GOSUB 100 : PRINT "F0E base 16 :" N
90 END
100 REM SUM DIGITS OF N$, B
110 IF B = 1 THEN N = LEN(N$) : RETURN
120 IF B < 2 THEN B = 10
130 N = 0
140 V$ = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", B)
150 FOR I = 1 TO LEN(N$)
160 C$ = MID$(N$, I, 1)
170 FOR J = 1 TO LEN(V$)
180 IF C$ <> MID$(V$, J, 1) THEN NEXT J : N = SQR(-1) : STOP
190 N = N + J - 1
200 NEXT I
210 RETURN</syntaxhighlight>
{{out}}
<pre>Similar to FreeBASIC entry.</pre>
 
==={{header|Palo Alto Tiny BASIC}}===
{{trans|Tiny BASIC}}
Only base ten is supported. Palo Alto Tiny BASIC does not support operations on strings.
<syntaxhighlight lang="basic">
10 REM SUM DIGITS OF AN INTEGER
20 INPUT "ENTER A NUMBER"N
30 LET N=ABS(N),U=0
40 IF N=0 GOTO 80
50 LET U=U+N-N/10*10
60 LET N=N/10
70 GOTO 40
80 PRINT "ITS DIGIT SUM:",U
90 STOP</syntaxhighlight>
{{out}}
<pre>ENTER A NUMBER:-12321
ITS DIGIT SUM: 9</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">EnableExplicit
 
Procedure.i SumDigits(Number.q, Base)
If Number < 0 : Number = -Number : EndIf; convert negative numbers to positive
If Base < 2 : Base = 2 : EndIf ; base can't be less than 2
Protected sum = 0
While Number > 0
sum + Number % Base
Number / Base
Wend
ProcedureReturn sum
EndProcedure
If OpenConsole()
PrintN("The sums of the digits are:")
PrintN("")
PrintN("1 base 10 : " + SumDigits(1, 10))
PrintN("1234 base 10 : " + SumDigits(1234, 10))
PrintN("fe base 16 : " + SumDigits($fe, 16))
PrintN("f0e base 16 : " + SumDigits($f0e, 16))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf</syntaxhighlight>
{{out}}
<pre>
The sums of the digits are:
 
1 base 10 : 1
1234 base 10 : 10
fe base 16 : 29
f0e base 16 : 29
</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight QBasiclang="qbasic">FUNCTION SumDigits (number, nBase)
IF number < 0 THEN number = -number
IF nBase < 2 THEN nBase = 2
Line 833 ⟶ 1,101:
PRINT "fe base 16 :"; SumDigits(&HFE, 16)
PRINT "f0e base 16 :"; SumDigits(&HF0E, 16)
END</langsyntaxhighlight>
 
==={{header|True BASIC}}===
<lang qbasic>FUNCTION SumDigits(number, nBase)
IF number < 0 THEN LET number = -number
IF nBase < 2 THEN LET nBase = 2
LET sum = 0
 
DO WHILE number > 0
LET sum = sum + REMAINDER(number, nBase)
LET number = INT(number / nBase)
LOOP
 
LET SumDigits = sum
END FUNCTION
 
PRINT "The sums of the digits are:"
PRINT
PRINT "1 base 10 :"; SumDigits(1, 10)
PRINT "1234 base 10 :"; SumDigits(1234, 10)
PRINT "fe base 16 :"; SumDigits(254, 16) !0xfe
PRINT "f0e base 16 :"; SumDigits(3854, 16) !0xf0e
END</lang>
 
==={{header|Yabasic}}===
<lang yabasic>sub SumDigits(number, nBase)
if number < 0 then number = -number : fi
if nBase < 2 then nBase = 2 : fi
sum = 0
while number > 0
sum = sum + mod(number, nBase)
number = int(number / nBase)
wend
return sum
end sub
 
print "The sums of the digits are:\n"
print "1 base 10 : ", SumDigits(1, 10)
print "1234 base 10 : ", SumDigits(1234, 10)
print "fe base 16 : ", SumDigits(0xfe, 16)
print "f0e base 16 : ", SumDigits(0xf0e, 16)
end</lang>
 
==={{header|QuickBASIC}}===
Line 880 ⟶ 1,107:
{{works with|QB64}}
{{works with|VB-DOS}}
<syntaxhighlight lang="qbasic">DECLARE FUNCTION SumDigits% (Num AS INTEGER, NBase AS INTEGER)
<lang qbasic>
DECLARE FUNCTION SumDigits% (Num AS INTEGER, NBase AS INTEGER)
 
CLS
Line 900 ⟶ 1,126:
LOOP
SumDigits% = iSum
END FUNCTION</syntaxhighlight>
</lang>
 
{{out}}
<pre>
Line 910 ⟶ 1,134:
F0E base 16 -> 20
</pre>
 
==={{header|Run BASIC}}===
{{trans|BASIC256}}
<syntaxhighlight lang="vb">function SumDigits(number, nBase)
if number < 0 then number = -1 * number ' convert negative numbers to positive
if nBase < 2 then nBase = 2 ' nBase can//t be less than 2
sum = 0
while number > 0
sum = sum + (number mod nBase)
number = int(number / nBase)
wend
SumDigits = sum
end function
 
print "The sums of the digits are:\n"
print "1 base 10 : "; SumDigits(1, 10)
print "1234 base 10 : "; SumDigits(1234, 10)
print "fe base 16 : "; SumDigits(hexdec("FE"), 16)
print "f0e base 16 : "; SumDigits(hexdec("F0E"), 16)
 
==={{header|TI-83 BASIC}}===
<syntaxhighlight lang="ti-83b">"01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str1
Disp "SUM DIGITS OF INT"
Disp "-----------------"
Disp "ENTER NUMBER"
Input Str2
Disp "ENTER BASE"
Input B
0→R
length(Str2)→L
For(I,1,L,1)
sub(Str2,I,1)→Str3
inString(Str1,Str3)-1→S
If S≥B or S=-1:Then
Disp "ERROR:"
Disp Str3
Disp "NOT IN BASE"
Disp B
Stop
End
R+S→R
End
Disp R</syntaxhighlight>
 
==={{header|Tiny BASIC}}===
Only base ten is supported because the only data type is signed 16-bit int.
<langsyntaxhighlight lang="tinybasic">
PRINT "Enter a number."
INPUT N
Line 923 ⟶ 1,190:
GOTO 10
20 PRINT "Its digit sum is ",S,"."
END</langsyntaxhighlight>
{{out}}
<pre>Enter a number.
Line 929 ⟶ 1,196:
Its digit sum is 7.</pre>
 
==={{header|BBCTrue BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION SumDigits(number, nBase)
{{works with|BBC BASIC for Windows}}
IF number < 0 THEN LET number = -number
This solution deliberately avoids MOD and DIV so it is not restricted to 32-bit integers.
IF nBase < 2 THEN LET nBase = 2
<lang bbcbasic> *FLOAT64
LET sum = 0
PRINT "Digit sum of 1 (base 10) is "; FNdigitsum(1, 10)
 
PRINT "Digit sum of 12345 (base 10) is "; FNdigitsum(12345, 10)
DO WHILE number > 0
PRINT "Digit sum of 9876543210 (base 10) is "; FNdigitsum(9876543210, 10)
PRINT "DigitLET sum of= FEsum (base+ 16) is "; ~FNdigitsumREMAINDER(&FEnumber, 16) " (base 16nBase)"
LET number = INT(number / nBase)
PRINT "Digit sum of F0E (base 16) is "; ~FNdigitsum(&F0E, 16) " (base 16)"
ENDLOOP
 
LET SumDigits = sum
DEF FNdigitsum(n, b)
END FUNCTION
LOCAL q, s
 
WHILE n <> 0
PRINT "The sums of the digits are:"
q = INT(n / b)
PRINT
s += n - q * b
PRINT "1 base 10 :"; nSumDigits(1, = q10)
PRINT "1234 base 10 :"; SumDigits(1234, 10)
ENDWHILE
PRINT "fe base 16 :"; SumDigits(254, 16) !0xfe
= s</lang>
PRINT "f0e base 16 :"; SumDigits(3854, 16) !0xf0e
{{out}}
END</syntaxhighlight>
 
==={{header|Visual Basic}}===
This version checks that only valid digits for the indicated base are passed in, exiting otherwise.
 
<syntaxhighlight lang="vb">Function sumDigits(num As Variant, base As Long) As Long
'can handle up to base 36
Dim outp As Long
Dim validNums As String, tmp As Variant, x As Long, lennum As Long
'ensure num contains only valid characters
validNums = Left$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", base)
lennum = Len(num)
For L0 = lennum To 1 Step -1
x = InStr(validNums, Mid$(num, L0, 1)) - 1
If -1 = x Then Exit Function
tmp = tmp + (x * (base ^ (lennum - L0)))
Next
While tmp
outp = outp + (tmp Mod base)
tmp = tmp \ base
Wend
sumDigits = outp
End Function
 
Sub tester()
Debug.Print sumDigits(1, 10)
Debug.Print sumDigits(1234, 10)
Debug.Print sumDigits(&HFE, 16)
Debug.Print sumDigits(&HF0E, 16)
Debug.Print sumDigits("2", 2)
End Sub</syntaxhighlight>
{{out}} (in the debug window):
<pre>
1
Digit sum of 1 (base 10) is 1
10
Digit sum of 12345 (base 10) is 15
11
Digit sum of 9876543210 (base 10) is 45
20
Digit sum of FE (base 16) is 1D (base 16)
0
Digit sum of F0E (base 16) is 1D (base 16)
</pre>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Sum digits of an integer"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
DECLARE FUNCTION SumDigits (number, nBase)
 
FUNCTION Entry ()
PRINT "The sums of the digits are:"
PRINT
PRINT "1 base 10 : "; SumDigits(1, 10)
PRINT "1234 base 10 : "; SumDigits(1234, 10)
PRINT "fe base 16 : "; SumDigits(0xfe, 16)
PRINT "f0e base 16 : "; SumDigits(0xf0e, 16)
END FUNCTION
 
FUNCTION SumDigits (number, nBase)
IF number < 0 THEN number = -number
IF nBase < 2 THEN nBase = 2
sum = 0
DO WHILE number > 0
sum = sum + (number MOD nBase)
number = number / nBase
LOOP
RETURN sum
END FUNCTION
END PROGRAM</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">sub SumDigits(number, nBase)
if number < 0 then number = -number : fi
if nBase < 2 then nBase = 2 : fi
sum = 0
while number > 0
sum = sum + mod(number, nBase)
number = int(number / nBase)
wend
return sum
end sub
 
print "The sums of the digits are:\n"
print "1 base 10 : ", SumDigits(1, 10)
print "1234 base 10 : ", SumDigits(1234, 10)
print "fe base 16 : ", SumDigits(0xfe, 16)
print "f0e base 16 : ", SumDigits(0xf0e, 16)
end</syntaxhighlight>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">define s(n) {
auto i, o, s
Line 977 ⟶ 1,324:
ibase = 16
s(FE)
s(F0E)</langsyntaxhighlight>
 
{{Out}}
Line 986 ⟶ 1,333:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let digitsum(n, base) =
Line 998 ⟶ 1,345:
writef("%N*N", digitsum(#XFE, 16)) // prints 29
writef("%N*N", digitsum(#XF0E, 16)) // also prints 29
$)</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,010 ⟶ 1,357:
This solution reads the number and base as integers from stdin (in base 10). There doesn't seem any point in accepting input in other bases, because it would then have to be processed as a string and the base would be irrelevant, defeating the point of this exercise.
 
<langsyntaxhighlight lang="befunge">" :rebmuN">:#,_&0v
|_,#!>#:<"Base: "<
<>10g+\00g/:v:p00&
v^\p01<%g00:_55+\>
>" :muS">:#,_$\.,@</langsyntaxhighlight>
 
{{out}}
Line 1,026 ⟶ 1,373:
 
Default base(right argument) is 10.
<langsyntaxhighlight lang="bqn">SumDigits ← {
𝕊 𝕩: 10 𝕊 𝕩;
𝕨 𝕊 0: 0;
Line 1,034 ⟶ 1,381:
•Show SumDigits 1
•Show SumDigits 1234
•Show 16 SumDigits 254</langsyntaxhighlight>
<syntaxhighlight lang="text">1
10
29</langsyntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=U3VtRGlnaXRzIOKGkCB7CiAg8J2ViiDwnZWpOiAxMCDwnZWKIPCdlak7CiAg8J2VqCDwnZWKIDA6IDA7CiAgKPCdlah88J2VqSkr8J2VqPCdlYrijIrwnZWpw7fwnZWoCn0KCuKAolNob3cgU3VtRGlnaXRzIDEK4oCiU2hvdyBTdW1EaWdpdHMgMTIzNArigKJTaG93IDE2IFN1bURpZ2l0cyAyNTQ= Try It!]
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int SumDigits(unsigned long long n, const int base) {
Line 1,059 ⟶ 1,406:
SumDigits(0xf0e, 16) );
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>1 15 15 29 29</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">namespace RosettaCode.SumDigitsOfAnInteger
{
using System;
Line 1,121 ⟶ 1,468:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,130 ⟶ 1,477:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cmath>
int SumDigits(const unsigned long long int digits, const int BASE = 10) {
Line 1,151 ⟶ 1,498:
<< SumDigits(0xf0e, 16) << std::endl;
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>1 15 15 29 29</pre>
Line 1,157 ⟶ 1,504:
===Template metaprogramming version===
Tested with g++-4.6.3 (Ubuntu).
<langsyntaxhighlight lang="cpp">
// Template Metaprogramming version by Martin Ettl
#include <iostream>
Line 1,191 ⟶ 1,538:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>1 15 15 29 29</pre>
 
=={{header|Chez Scheme}}==
<syntaxhighlight lang="scheme">
(define dsum (lambda (x base)
(let ((number (if (string? x) (string->number x base) x)))
(if (= (string-length (number->string number)) 1) number
(+ (mod number base) (dsum (div number base) base))))))
> (dsum 123 10)
6
> (dsum "fe" 16)
29
> (dsum "f0e" 16)
29
> (dsum 1234 10)
10
 
</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn sum-digits [n base]
(let [number (if-not (string? n) (Long/toString n base) n)]
(reduce + (map #(Long/valueOf (str %) base) number))))</langsyntaxhighlight>
 
{{out}}
Line 1,219 ⟶ 1,583:
user=> (sum-digits "clojure" 32)
147</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Find the digits of a number in a given base
digits = iter (n, base: int) yields (int)
while n>0 do
yield(n // base)
n := n / base
end
end digits
 
% Sum the digits of a number in a given base
digitsum = proc (n, base: int) returns (int)
sum: int := 0
for digit: int in digits(n, base) do
sum := sum + digit
end
return(sum)
end digitsum
 
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, int$unparse(digitsum(1, 10)))
stream$putl(po, int$unparse(digitsum(1234, 10)))
stream$putl(po, int$unparse(digitsum(254, 16))) % 0xFE = 254
stream$putl(po, int$unparse(digitsum(3854, 16))) % 0xF0E = 3854
end start_up</syntaxhighlight>
{{out}}
<pre>1
10
29
29</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun sum-digits (number base)
(loop for n = number then q
for (q r) = (multiple-value-list (truncate n base))
sum r until (zerop q)))</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="lisp">(loop for (number base) in '((1 10) (1234 10) (#xfe 16) (#xf0e 16))
do (format t "(~a)_~a = ~a~%" number base (sum-digits number base)))</langsyntaxhighlight>
{{out}}
<pre>(1)_10 = 1
Line 1,236 ⟶ 1,632:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub digitSum(n: uint32, base: uint32): (r: uint32) is
Line 1,253 ⟶ 1,649:
print_nl();
print_i32(digitSum(0xF0E, 16)); # prints 29
print_nl();</langsyntaxhighlight>
 
{{out}}
Line 1,263 ⟶ 1,659:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">class String
def sum_digits(base : Int) : Int32
self.chars.reduce(0) { |acc, c|
Line 1,275 ⟶ 1,671:
puts("1234".sum_digits 10)
puts("fe".sum_digits 16)
puts("f0e".sum_digits 16)</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,284 ⟶ 1,680:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.bigint;
 
uint sumDigits(T)(T n, in uint base=10) pure nothrow
Line 1,302 ⟶ 1,698:
sumDigits(0xf0e, 16).writeln;
1_234.BigInt.sumDigits.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,309 ⟶ 1,705:
29
10</pre>
 
=={{header|Dart}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="dart">import 'dart:math';
 
num sumDigits(var number, var nBase) {
if (number < 0) number = -number; // convert negative numbers to positive
if (nBase < 2) nBase = 2; // nBase can't be less than 2
num sum = 0;
while (number > 0) {
sum += number % nBase;
number ~/= nBase;
}
return sum;
}
 
void main() {
print('The sums of the digits are:\n');
print('1 base 10 : ${sumDigits(1, 10)}');
print('1234 base 10 : ${sumDigits(1234, 10)}');
print('fe base 16 : ${sumDigits(0xfe, 16)}');
print('f0e base 16 : ${sumDigits(0xf0e, 16)}');
}</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|Dc}}==
<langsyntaxhighlight lang="d">[ I ~ S! d 0!=S L! + ] sS
 
1 lS x p
Line 1,317 ⟶ 1,738:
16 i
FE lS x p
F0E lS x p</langsyntaxhighlight>
{{out}}
<pre>
Line 1,330 ⟶ 1,751:
{{trans|C#}}
 
<langsyntaxhighlight lang="dyalect">func digits(num, bas = 10) {
while num != 0 {
let (n, digit) = (num / bas, num % bas)
Line 1,355 ⟶ 1,776:
] {
print(sumOfDigits(e.num, e.bas))
}</langsyntaxhighlight>
 
{{out}}
Line 1,367 ⟶ 1,788:
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Sum_digits_of_an_integer#Pascal Pascal].
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec digitsum(word n; byte base) byte:
byte sum;
sum := 0;
while n>0 do
sum := sum + n % base;
n := n / base
od;
sum
corp
 
proc nonrec main() void:
writeln(digitsum(1, 10));
writeln(digitsum(1234, 10));
writeln(digitsum(0xFE, 16));
writeln(digitsum(0xF0E, 16))
corp</syntaxhighlight>
{{out}}
<pre>1
10
29
29</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func sumdig s$ .
for c$ in strchars s$
h = strcode c$ - 48
if h >= 10
h -= 39
.
r += h
.
return r
.
print sumdig "1"
print sumdig "1234"
print sumdig "fe"
print sumdig "f0e"
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
Numbers on the simulated input tape have to be in decimal (not a serious restriction, as pointed out in the Befunge solution). The EDSAC subroutine library didn't include a routine for integer division, so we have to write our own. In the test values, decimal 2003579 represents base-36 16xyz from Kotlin.
<syntaxhighlight lang="edsac">
[Sum of digits of a number in a given base - Rosetta Code
EDSAC program (Initial Orders 2)]
 
[Arrange the storage]
T45K P56F [H parameter: library subroutine R4 to read integer]
T46K P80F [N parameter: subroutine to print 35-bit positive integer]
T47K P180F [M parameter: main routine]
T48K P120F [& (Delta) parameter: subroutine for integer division]
T51K P157F [G parameter: subroutine to find sum of digits]
 
[Library subroutine M3, runs at load time and is then overwritten.
Prints header; here, last character sets teleprinter to figures.]
PF GK IF AF RD LF UF OF E@ A6F G@ E8F EZ PF
*!!!!NUMBER!!!!!!!BASE!!!SUM!OF!DIGITS@&#..PZ
 
[============== G parameter: Subroutine find sum of digits ==============
Input: 4D = non-negative number (not preserved)
6D = base (not preserved)
Output: 0D = sum of digits
Workspace: 8D (in called subroutine), 10D, 12D]
E25K TG GK
A3F T22@ [plant return link as usual]
A6D T10D [store base in 10D]
T12D [sum of digits in 12D, initialize to 0]
A4D [acc := number]
E17@ [jump into middle of loop]
[Start of loop. Next dividend is already in 4D.]
[7] TF [clear acc]
A10D T6D [pass base as divisor]
[10] A10@ G& [call division subroutine]
A4D A12D T12D [remainder is next digit; add to result]
A6D U4D [quotient becomes next dividend]
[17] S10D [is dividend >= base?]
E7@ [if so, loop back to do division]
[Here if dividend < base. Means that dividend = top digit.]
A10D [restore digit after test]
A12D [add to sum of digits]
TD [return sum of digits in 0D]
[22] ZF [(planted) jump back to caller]
 
[====================== M parameter: Main routine ======================]
E25K TM GK
[Load at even addess; put 35-bit values first]
[0] PF PF [number]
[2] PF PF [base]
[4] PF [negative data count]
[5] !F [space]
[6] @F [carriage return]
[7] &F [line feed]
[8] K4096F [null character]
[Enter with acc = 0]
[9] A9@ GH [call subroutine R4, sets 0D := count of (n,k) pairs]
SF [acc := count negated; it's assumed that count < 2^16]
E48@ [exit if count = 0]
LD [shift count into address field]
[14] T4@ [update negative loop counter]
[15] A15@ GH [call library subroutine R4, 0D := number]
AD T#@ [store number]
[19] A19@ GH [call library subroutine R4, 0D := base]
AD T2#@ [store base]
A#@ TD [pass number to print subroutine]
[25] A25@ GN O5@ [print number, plus space]
A2#@ TD [pass base to print subroutine]
[30] A30@ GN O5@ O5@ O5@ [print base, plus spaces]
A#@ T4D [pass number to sum-of-digits subroutine]
A2#@ T6D [same for base]
[39] A39@ GG [call subroutine, 0D := sum of digits]
[41] A41@ GN O6@ O7@ [print sum of digits, plus CR,LF]
A4@ A2F [increment negative counter]
G14@ [loop back if still negative]
[48] O8@ [done; print null to flush printer buffer]
ZF [halt the machine]
 
[The next 3 lines put the entry address into location 50,
so that it can be accessed via the X parameter (see end of program).]
T50K
P9@
T9Z
 
[================== H parameter: Library subroutine R4 ==================
Input of one signed integer, returned in 0D.
22 locations.]
E25K TH GK
GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF
 
[============================= N parameter ==============================
Library subroutine P7, prints long strictly positive integer in 0D.
10 characters, right justified, padded left with spaces.
Even address; 35 storage locations; working position 4D.]
E25K TN
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F
T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
 
[========================== & (Delta) parameter ==========================]
[The following subroutine is not in the EDSAC library.
Division subroutine for positive 35-bit integers,
returning quotient and remainder.
Input: dividend at 4D, divisor at 6D
Output: remainder at 4D, quotient at 6D.
37 locations; working locations 0D, 8D.]
E25K T&
GKA3FT35@A6DU8DTDA4DRDSDG13@T36@ADLDE4@T36@T6DA4DSDG23@
T4DA6DYFYFT6DT36@A8DSDE35@T36@ADRDTDA6DLDT6DE15@EFPF
 
[==========================================================================]
[On the original EDSAC, the following (without the whitespace and comments)]
[might have been input on a separate tape.]
E25K TX GK
EZ [define entry point]
PF [acc = 0 on entry]
[Count of (n,k) pairs, then the pairs, to be read by library subroutine R4.]
[Note that sign comes *after* value.]
10+1+10+1234+10+254+16+3854+16+2186+3+2187+3+123045+50+2003579+36+
123456789+1000+1234567890+100000+
</syntaxhighlight>
{{out}}
<pre>
NUMBER BASE SUM OF DIGITS
1 10 1
1234 10 10
254 16 29
3854 16 29
2186 3 14
2187 3 1
123045 50 104
2003579 36 109
123456789 1000 1368
1234567890 100000 80235
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def sumDigits(n, base\\10)
def sumDigits(n, base) when is_integer(n) do
Line 1,385 ⟶ 1,980:
Enum.each([{"1", 10}, {"1234", 10}, {"fe", 16}, {"f0e", 16}], fn {n,base} ->
IO.puts "#{n}(#{base}) sums to #{ RC.sumDigits(n,base) }"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,401 ⟶ 1,996:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(defun digit-sum (n)
(apply #'+ (mapcar (lambda (c) (- c ?0)) (string-to-list "123"))))
 
(digit-sum 1234) ;=> 10</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(sum_digits).
-export([sum_digits/2, sum_digits/1]).
Line 1,423 ⟶ 2,018:
sum_digits(N,B,Acc) ->
sum_digits(N div B, B, Acc + (N rem B)).
</syntaxhighlight>
</lang>
 
Example usage:
Line 1,446 ⟶ 2,041:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">digitSum
=LAMBDA(s,
FOLDROW(
Line 1,476 ⟶ 2,071:
)
)
)</langsyntaxhighlight>
 
and also assuming the following generic bindings in the Name Manager for the WorkBook:
 
<langsyntaxhighlight lang="lisp">CHARSROW
=LAMBDA(s,
MID(s,
Line 1,535 ⟶ 2,130:
)
)
)</langsyntaxhighlight>
 
{{Out}}
Line 1,589 ⟶ 2,184:
 
=={{header|Ezhil}}==
<syntaxhighlight lang="python">
<lang Python>
# இது ஒரு எழில் தமிழ் நிரலாக்க மொழி உதாரணம்
 
Line 1,609 ⟶ 2,204:
பதிப்பி எண்_கூட்டல்( 1289)#20
பதிப்பி எண்_கூட்டல்( 123456789)# 45
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let digsum b n =
Line 1,629 ⟶ 2,224:
 
show [1; 10; 1234; 10; 0xFE; 16; 0xF0E; 16] // -> 1 10 29 29
0</langsyntaxhighlight>
 
===or Generically===
In order to complete the [[Digital root]] task I require a function which can handle numbers larger than 32 bit integers.
<langsyntaxhighlight lang="fsharp">
//Sum Digits of An Integer - Nigel Galloway: January 31st., 2015
//This code will work with any integer type
Line 1,639 ⟶ 2,234:
let rec sum(g, n) = if n < BASE then n+g else sum(g+n%BASE, n/BASE)
sum(LanguagePrimitives.GenericZero<_>,N)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,662 ⟶ 2,257:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: sum-digits ( base n -- sum ) 0 swap [ dup zero? ] [ pick /mod swapd + swap ] until drop nip ;
 
{ 10 10 16 16 } { 1 1234 0xfe 0xf0e } [ sum-digits ] 2each</langsyntaxhighlight>
{{out}}
<pre>--- Data stack:
Line 1,674 ⟶ 2,269:
=={{header|Forth}}==
This is an easy task for Forth, that has built in support for radices up to 36. You set the radix by storing the value in variable BASE.
<langsyntaxhighlight lang="forth">: sum_int 0 begin over while swap base @ /mod swap rot + repeat nip ;
 
2 base ! 11110 sum_int decimal . cr
10 base ! 12345 sum_int decimal . cr
16 base ! f0e sum_int decimal . cr</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,686 ⟶ 2,281:
Other solutions ignore the representations of the input, encode digits using the base, then sum the encoding.
Both methods appear in this implementation.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Fri Jun 7 21:00:12
Line 1,778 ⟶ 2,373:
end subroutine process0
end program digit_sum
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
{{trans|PureBasic}}
<lang freebasic>' FB 1.05.0 Win64
 
Function SumDigits(number As Integer, nBase As Integer) As Integer
If number < 0 Then number = -number ' convert negative numbers to positive
If nBase < 2 Then nBase = 2 ' nBase can't be less than 2
Dim As Integer sum = 0
While number > 0
sum += number Mod nBase
number \= nBase
Wend
Return sum
End Function
Print "The sums of the digits are:"
Print
Print "1 base 10 :"; SumDigits(1, 10)
Print "1234 base 10 :"; SumDigits(1234, 10)
Print "fe base 16 :"; SumDigits(&Hfe, 16)
Print "f0e base 16 :"; SumDigits(&Hf0e, 16)
Print
Print "Press any key to quit the program"
Sleep</lang>
 
{{out}}
<pre>
The sums of the digits are:
 
1 base 10 : 1
1234 base 10 : 10
fe base 16 : 29
f0e base 16 : 29
</pre>
 
=={{header|Frink}}==
In Frink numbers can be specifed to an arbitrary base from 2 to 36 as <CODE>number\\base</CODE>. The function <CODE>integerDigits[n, base]</CODE> lists the digits of <CODE>n</CODE> in the base <CODE>base</CODE>.
<langsyntaxhighlight lang="frink">sumDigits[n, base=10] := sum[integerDigits[n, base]]</langsyntaxhighlight>
 
The sample problems can be written as:
<langsyntaxhighlight lang="frink">
sumDigits[1]
sumDigits[1234]
sumDigits[fe\\16]
sumDigits[f03\\16]
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sum_digits_of_an_integer}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
 
[[File:Fōrmulæ - Sum digits of an integer 01.png]]
 
'''Test cases'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Sum digits of an integer 02.png]]
In '''[https://formulae.org/?example=Sum_digits_of_an_integer this]''' page you can see the program(s) related to this task and their results.
 
[[File:Fōrmulæ - Sum digits of an integer 03.png]]
 
[[File:Fōrmulæ - Sum digits of an integer 04.png]]
 
[[File:Fōrmulæ - Sum digits of an integer 05.png]]
 
[[File:Fōrmulæ - Sum digits of an integer 06.png]]
 
[[File:Fōrmulæ - Sum digits of an integer 07.png]]
 
[[File:Fōrmulæ - Sum digits of an integer 08.png]]
 
[[File:Fōrmulæ - Sum digits of an integer 07.png]]
 
=={{header|Go}}==
Handling numbers up to 2^64-1 and bases from 2 to 36 is pretty easy, larger values can be handled using the <code>math/big</code> package (but it's still limited to base<=36).
<langsyntaxhighlight lang="go">// File digit.go
 
package digit
Line 1,877 ⟶ 2,455:
}
return
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">// File digit_test.go
 
package digit
Line 1,928 ⟶ 2,506:
t.Log("got expected error:", err)
}
}</langsyntaxhighlight>
 
 
=={{header|Golfscript}}==
<syntaxhighlight lang="golfscript">{base {+}*}:sd;</syntaxhighlight>
 
Test (apply sd for each array [number radix]) :
 
{{out}}
<pre>[[1 10] [1234 10] [254 16] [3854 16]] {~sd p}%
1
10
29
29
</pre>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def digitsum = { number, radix = 10 ->
Integer.toString(number, radix).collect { Integer.parseInt(it, radix) }.sum()
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">[[30, 2], [30, 10], [1, 10], [12345, 10], [123405, 10], [0xfe, 16], [0xf0e, 16]].each {
println """
Decimal value: ${it[0]}
Line 1,945 ⟶ 2,537:
Radix Digit Sum: ${Integer.toString(digitsum(it[0], it[1]), it[1])}
"""
}</langsyntaxhighlight>
 
{{out}}
Line 1,997 ⟶ 2,589:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">digsum
:: Integral a
=> a -> a -> a
Line 2,008 ⟶ 2,600:
 
main :: IO ()
main = print $ digsum 16 255 -- "FF": 15 + 15 = 30</langsyntaxhighlight>
{{Out}}
<pre>30</pre>
 
 
In terms of unfoldr:
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
import Data.Tuple (swap)
 
----------------- SUM DIGITS OF AN INTEGER ---------------
 
baseDigitSum :: Int -> Int -> Int
baseDigitSum base n = sum . unfoldr go
sum $where
unfoldr go x
| 0 < x = (Just . swap) $ quotRem x base
(\x ->
| otherwise if= 0 < xNothing
then Just $ swap $ quotRem x base
else Nothing)
n
 
-------------------------- TESTS -------------------------
main :: IO ()
main =
mapM_
print
[ baseDigitSum <$> [2, 8, 10, 16] <*> [255],
, baseDigitSum <$> [10] <*> [1, 1234],
, baseDigitSum <$> [16] <*> [0xfe, 0xf0e]
]</langsyntaxhighlight>
{{Out}}
<pre>[8,17,12,30]
Line 2,042 ⟶ 2,633:
 
Or, we could write '''sum . fmap digitToInt''', or the equivalent but more efficient fusion of it to a single fold: '''foldr ((+) . digitToInt) 0'''
<langsyntaxhighlight lang="haskell">import Data.Char (digitToInt, intToDigit, isHexDigit)
import Data.List (transpose)
import Numeric (readInt, showIntAtBase)
Line 2,099 ⟶ 2,690:
readBase b s = n
where
[(n, _)] = readInt b isHexDigit digitToInt s</langsyntaxhighlight>
{{Out}}
<pre> Base Digits Value digit string -> sum integer value -> sum
Line 2,113 ⟶ 2,704:
some of the other solutions.
 
<langsyntaxhighlight lang="unicon">procedure main(a)
write(dsum(a[1]|1234,a[2]|10))
end
Line 2,122 ⟶ 2,713:
while sum +:= (0 < n) % b do n /:= b
return sum
end</langsyntaxhighlight>
 
Sample runs:
Line 2,148 ⟶ 2,739:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">digsum=: 10&$: : (+/@(#.inv))</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> digsum 1234
10
10 digsum 254
11
16 digsum 254
29</langsyntaxhighlight>
 
Illustration of mechanics:
 
<langsyntaxhighlight lang="j"> 10 #. 1 2 3 4
1234
10 #.inv 1234
Line 2,168 ⟶ 2,759:
10
10 +/@(#.inv) 1234
10</langsyntaxhighlight>
 
So #.inv gives us the digits, +/ gives us the sum, and @ glues them together with +/ being a "post processor" for #.inv or, as we say in the expression: (#.inv). We need the parenthesis or inv will try to look up the inverse of +/@#. and that's not well defined.
Line 2,176 ⟶ 2,767:
Full examples:
 
<langsyntaxhighlight lang="j"> digsum 1
1
digsum 1234
Line 2,183 ⟶ 2,774:
29
16 digsum 16bf0e
29</langsyntaxhighlight>
 
Note that J implements numeric types -- J tries to ensure that the semantics of numbers match their mathematical properties. So it doesn't matter how we originally obtained a number.
 
<langsyntaxhighlight lang="j"> 200+54
254
254
Line 2,196 ⟶ 2,787:
254
254b10 , 1r254b0.1 NB. 10 in base 254 , 0.1 in base 1/254
254 254</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.math.BigInteger;
public class SumDigits {
public static int sumDigits(long num) {
Line 2,230 ⟶ 2,821:
System.out.println(sumDigits(new BigInteger("12345678901234567890")));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,244 ⟶ 2,835:
 
===Imperative===
<syntaxhighlight lang="javascript">function sumDigits(n) {
 
<lang JavaScript>function sumDigits(n) {
n += ''
for (var s=0, i=0, e=n.length; i<e; i+=1) s+=parseInt(n.charAt(i),36)
Line 2,251 ⟶ 2,841:
}
for (var n of [1, 12345, 0xfe, 'fe', 'f0e', '999ABCXYZ']) document.write(n, ' sum to ', sumDigits(n), '<br>')
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,262 ⟶ 2,852:
</pre>
 
===Functional (ES 5)===
====ES5====
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 2,290 ⟶ 2,880:
.join('\n');
 
})();</syntaxhighlight>
<pre>1 -> 1
</lang>
12345 -> 15
254 -> 11
fe -> 29
f0e -> 29
999ABCXYZ -> 162</pre>
 
====ES6====
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// -------------- INTEGER DIGITS SUMMED --------------
 
// digitsSummed :: (Int | String) -> Int
const digitsSummed = number => {
 
// 10 digits + 26 alphabetics
// give us glyphs for up to base 36
const intMaxBase = 36;
 
return `${number}`
.split("")
.reduce(
(sofar, digit) => sofar + parseInt(
digit, intMaxBase
),
0
);
};
 
// ---------------------- TEST -----------------------
return [1, 12345, 0xfe, "fe", "f0e", "999ABCXYZ"]
.map((x) => `${x} -> ${digitsSummed(x)}`)
.join("\n");
})();</syntaxhighlight>
{{Out}}
<pre>1 -> 1
12345 -> 15
Line 2,300 ⟶ 2,923:
f0e -> 29
999ABCXYZ -> 162</pre>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE digitsum ==
[swap string] [dup [strtol] dip] [] ifte
[<] [pop] [dup rollup div rotate] [+] linrec.
 
1 10 digitsum.
1234 10 digitsum.
"fe" 16 digitsum.
"f0e" 16 digitsum.
</syntaxhighlight>
{{out}}
<pre>1
10
29
29</pre>
 
=={{header|jq}}==
The following pipeline will have the desired effect if numbers and/or strings are presented as input:
<langsyntaxhighlight lang="jq">tostring | explode | map(tonumber - 48) | add</langsyntaxhighlight>
For example:<langsyntaxhighlight lang="sh">
$ jq -M 'tostring | explode | map(tonumber - 48) | add'
123
6
"123"
6</langsyntaxhighlight>
 
=={{header|Julia}}==
Using the built-in <code>digits</code> function:
<langsyntaxhighlight lang="julia">sumdigits(n, base=10) = sum(digits(n, base))</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
const val digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Line 2,337 ⟶ 2,976:
println("The sum of digits is:")
for ((number, base) in numbers) println("$number\tbase $base\t-> ${sumDigits(number, base)}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,350 ⟶ 2,989:
16xyz base 36 -> 109
</pre>
 
=={{header|Lambdatalk}}==
Following Javascript, with 10 digits + 26 alphabetics giving us glyphs for up to base 36
<syntaxhighlight lang="scheme">
{def sum_digits
{lambda {:n}
{if {W.empty? {W.rest :n}}
then {parseInt {W.first :n} 36}
else {+ {parseInt {W.first :n} 36} {sum_digits {W.rest :n}}}}}}
-> sum_digits
 
{S.map {lambda {:i} {div}:i sum to {sum_digits :i}}
1 12345 0xfe fe f0e 999ABCXYZ}
->
1 sum to 1
12345 sum to 15
0xfe sum to 62
fe sum to 29
f0e sum to 29
999ABCXYZ sum to 162
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define br => '<br />\n'
 
define sumdigits(int, base = 10) => {
Line 2,376 ⟶ 3,037:
sumdigits(0xfe, 16)
br
sumdigits(0xf0e, 16)</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,385 ⟶ 3,046:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on sum_digits (n, base)
sum = 0
repeat while n
Line 2,393 ⟶ 3,054:
end repeat
return sum
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">put sum_digits(1, 10)
-- 1
put sum_digits(1234, 10)
Line 2,402 ⟶ 3,063:
-- 29
put sum_digits(3854, 16) -- 0xf0e
-- 29</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function sumDigits n, base
local numb
if base is empty then put 10 into base
Line 2,412 ⟶ 3,073:
end repeat
return numb
end sumDigits</langsyntaxhighlight>
Example
<langsyntaxhighlight LiveCodelang="livecode">put sumdigits(1,10) & comma & \
sumdigits(1234,10) & comma & \
sumdigits(fe,16) & comma & \
sumdigits(f0e,16)</langsyntaxhighlight>Output<syntaxhighlight lang LiveCode="livecode">1,10,29,29</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">make "digits "0123456789abcdefghijklmnopqrstuvwxyz
 
to digitvalue :digit
Line 2,430 ⟶ 3,091:
end
 
foreach [1 1234 fe f0e] [print (se ? "-> sumdigits ?)]</langsyntaxhighlight>
 
{{Out}}
Line 2,439 ⟶ 3,100:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function sum_digits(n, base)
sum = 0
while n > 0.5 do
Line 2,453 ⟶ 3,114:
print(sum_digits(1234, 10))
print(sum_digits(0xfe, 16))
print(sum_digits(0xf0e, 16))</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,459 ⟶ 3,120:
29
29</pre>
 
=={{header|M2000 Interpreter}}==
 
<syntaxhighlight lang="m2000 interpreter">
module SumDigitisOfAnInteger {
z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sumdigits=lambda z (m as string) ->{
integer ret, i
m=ucase$(m)
if len(m)=0 then =ret:exit
for i=1 to len(m):ret+=instr(z, mid$(m,i,1))-1:next
=ret
}
CheckBase=lambda z (m as string, base as integer)->{
if len(m)=0 then Error "not valid input"
if base<2 or base>len(z) then Error "not valid input"
integer ret=1
m=ucase$(m)
for i=1 to len(m)
ret*=instr(z, mid$(m,i,1))<=base
if ret=0 then exit for
next
=ret<>0
}
string n
integer b
stack new {
data "1", 10
data "1234", 10
data ""+0xfe, 10
data "fe", 16
data "f0e", 16
while not empty
read n, b
Print n+" (base:"+b+") sums to "+sumdigits(n)
end while
}
Input "number, base :", n, b
if CheckBase(n, b) then
Print "sums to "+sumdigits(n)
else
Print n;" isn't a number of base "+b
end if
}
SumDigitisOfAnInteger
</syntaxhighlight>
{{out}}
<pre>
1 (base:10) sums to 1
1234 (base:10) sums to 10
254 (base:10) sums to 11
fe (base:16) sums to 29
f0e (base:16) sums to 29
number, base :12345671234567, 8
sums to 56
</pre>
 
 
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">sumDigits := proc( num )
local digits, number_to_string, i;
number_to_string := convert( num, string );
Line 2,468 ⟶ 3,187:
end proc:
sumDigits( 1234 );
sumDigits( "fe" );</langsyntaxhighlight>
{{out}}
<pre>
Line 2,476 ⟶ 3,195:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Total[IntegerDigits[1234]]
Total[IntegerDigits[16^^FE, 16]]</langsyntaxhighlight>
{{out}}
<pre>10
29</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map fmt tests))]
where tests = [(1,10), (1234,10), (0xfe,16), (0xf0e,16)]
fmt (d,b) = (shownum d) ++ "_" ++ (shownum b) ++ " -> " ++
(shownum (digitsum b d))
 
digitsum :: num->num->num
digitsum base 0 = 0
digitsum base n = n mod base + digitsum base (n div base)</syntaxhighlight>
{{out}}
<pre>1_10 -> 1
1234_10 -> 10
254_16 -> 29
3854_16 -> 29</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 <-> П1 Сx П2 ИП1 ^ ИП0 / [x]
П3 ИП0 * - ИП2 + П2 ИП3 П1 x=0
05 ИП2 С/П</langsyntaxhighlight>
 
=={{header|ML}}==
Function with first argument valid base, second argument number
<syntaxhighlight lang="standard ml">
<lang Standard ML>
local
open IntInf
Line 2,501 ⟶ 3,236:
summDigits 16 0xf0e ;
summDigits 4332489243570890023480923 0x8092eeac80923984098234098efad2109ce341000c3f0912527130 ;
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="standard ml">
<lang Standard ML>
val it = 1: IntInf.int
val it = 10: IntInf.int
Line 2,509 ⟶ 3,244:
val it = 29: IntInf.int
val it = 4745468831557628080368936: IntInf.int
</syntaxhighlight>
</lang>
 
==={{header|mLite}}===
Left in the to_radix even though not used in the solution.
<langsyntaxhighlight lang="ocaml">exception :radix_out_of_range and :unknown_digit;
 
fun to_radix (0, radix, result) = implode result
Line 2,554 ⟶ 3,289:
shosum ("1101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",2);
shosum ("thequickbrownfoxjumpsoverthelazydog",36);
</syntaxhighlight>
</lang>
Output
<pre>sum of digits of 10fg (base 17) = 32
Line 2,564 ⟶ 3,299:
{{trans|Pascal}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<langsyntaxhighlight lang="modula2">
MODULE SumOFDigits;
FROM STextIO IMPORT
Line 2,614 ⟶ 3,349:
WriteLn;
END SumOFDigits.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,627 ⟶ 3,362:
===Strings===
Processes data as text from the command line. Provides a representative sample if no input is supplied:
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,693 ⟶ 3,428:
 
return rVal
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,715 ⟶ 3,450:
===Type <tt>int</tt>===
Processes sample data as <tt>int</tt> arrays:
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 2,752 ⟶ 3,487:
iVal = Integer.valueOf(oVal, 8).intValue()
return iVal
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,765 ⟶ 3,500:
 
=={{header|Never}}==
<syntaxhighlight lang="never">
<lang Never>
func sum_digits(n : int, base : int) -> int {
var sum = 0;
Line 2,788 ⟶ 3,523:
0
}
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 2,799 ⟶ 3,534:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc sumdigits(n, base: Natural): Natural =
var n = n
while n > 0:
Line 2,809 ⟶ 3,544:
echo sumDigits(123045, 10)
echo sumDigits(0xfe, 16)
echo sumDigits(0xf0e, 16)</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,818 ⟶ 3,553:
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">
MODULE SumDigits;
IMPORT Out;
Line 2,838 ⟶ 3,573:
Out.String("OF0EH : ");Out.LongInt(Sum(0F0EH,16),10);Out.Ln
END SumDigits.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,848 ⟶ 3,583:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class SumDigits {
function : Main(args : String[]) ~ Nil {
SumDigit(1)->PrintLine();
Line 2,866 ⟶ 3,601:
}
}
</syntaxhighlight>
</lang>
 
{{output}}
Line 2,878 ⟶ 3,613:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let sum_digits ~digits ~base =
let rec aux sum x =
if x <= 0 then sum else
Line 2,891 ⟶ 3,626:
(sum_digits 123045 10)
(sum_digits 0xfe 16)
(sum_digits 0xf0e 16)</langsyntaxhighlight>
 
{{out}}
Line 2,898 ⟶ 3,633:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: sumDigits(n, base) 0 while( n ) [ n base /mod ->n + ] ;</langsyntaxhighlight>
 
Usage :
<langsyntaxhighlight Oforthlang="oforth">sumDigits(1, 10) println
sumDigits(1234, 10) println
sumDigits(0xfe, 16) println
sumDigits(0xf0e, 16) println</langsyntaxhighlight>
 
{{out}}
Line 2,915 ⟶ 3,650:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (sum n base)
(if (zero? n)
Line 2,932 ⟶ 3,667:
(print (sum #xf0e 16))
; ==> 29
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">dsum(n,base)=my(s); while(n, s += n%base; n \= base); s</langsyntaxhighlight>
 
Also the built-in <code>sumdigits</code> can be used for base 10.
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program SumOFDigits;
 
function SumOfDigitBase(n:UInt64;base:LongWord): LongWord;
Line 2,966 ⟶ 3,701:
writeln('18446744073709551615 sums to ', SumOfDigitBase(High(Uint64),10));
 
end.</langsyntaxhighlight>
;output:
<pre>
Line 2,976 ⟶ 3,711:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use warnings;
Line 2,992 ⟶ 3,727:
 
print "$_ sums to " . sumdigits($_) . "\n"
for (qw/1 1234 1020304 fe f0e DEADBEEF/);</langsyntaxhighlight>
{{out}}
<PRE>1 sums to 1
Line 3,002 ⟶ 3,737:
 
The ntheory module also does this, for a solution similar to Raku, with identical output.{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory "sumdigits";
say sumdigits($_,36) for (qw/1 1234 1020304 fe f0e DEADBEEF/);</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">sum_digits</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 3,021 ⟶ 3,756:
<span style="color: #0000FF;">?</span><span style="color: #000000;">sum_digits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">#FE</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">sum_digits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">#F0E</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,031 ⟶ 3,766:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function sumDigits($num, $base = 10) {
$s = base_convert($num, 10, $base);
Line 3,043 ⟶ 3,778:
echo sumDigits(0xfe, 16), "\n";
echo sumDigits(0xf0e, 16), "\n";
?></langsyntaxhighlight>
{{out}}
<pre>
Line 3,054 ⟶ 3,789:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
 
println(1=sum_digits(1)),
Line 3,131 ⟶ 3,866:
Map = new_map([A=I : {A,I} in zip(Alpha,0..length(Alpha)-1)]),
Len = N.length,
Res = sum([Map.get(D)*Base**(Len-I) : {D,I} in zip(N,1..N.length)]).</langsyntaxhighlight>
 
{{out}}
Line 3,163 ⟶ 3,898:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de sumDigits (N Base)
(or
(=0 N)
(+ (% N Base) (sumDigits (/ N Base) Base)) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (sumDigits 1 10)
-> 1
 
Line 3,178 ⟶ 3,913:
 
: (sumDigits (hex "f0e") 16)
-> 29</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
sum_digits: procedure options (main); /* 4/9/2012 */
declare ch character (1);
Line 3,197 ⟶ 3,932:
end;
end sum_digits;
</syntaxhighlight>
</lang>
results:
<pre>
Line 3,205 ⟶ 3,940:
SD= 5;
</pre>
 
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; GO TO 0; END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
 
PRINT$NUM: PROCEDURE (N);
DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P-1;
C = N MOD 10 + '0';
IF (N := N/10) > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUM;
 
DIGIT$SUM: PROCEDURE (N, BASE) BYTE;
DECLARE N ADDRESS, (BASE, SUM) BYTE;
SUM = 0;
DO WHILE N > 0;
SUM = SUM + N MOD BASE;
N = N / BASE;
END;
RETURN SUM;
END DIGIT$SUM;
 
CALL PRINT$NUM(DIGIT$SUM( 1, 10));
CALL PRINT$NUM(DIGIT$SUM( 1234, 10));
CALL PRINT$NUM(DIGIT$SUM( 0FEH, 16));
CALL PRINT$NUM(DIGIT$SUM(0F0EH, 16));
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre>1
10
29
29</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang Powershell>
function Get-DigitalSum ([string] $number, $base = 10)
{
Line 3,222 ⟶ 3,996:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,240 ⟶ 4,014:
 
==={{header|Alternative Implementation}}===
<syntaxhighlight lang="powershell">
<lang Powershell>
function Get-DigitalSum ([string] $number, $base = 10)
{
Invoke-Expression (($number.ToCharArray() | ForEach-Object {[string][convert]::ToInt16($_, $base)}) -join "+")
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,264 ⟶ 4,038:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">digit_sum(N, Base, Sum):-
digit_sum(N, Base, Sum, 0).
 
Line 3,284 ⟶ 4,058:
test_digit_sum(1234, 10),
test_digit_sum(0xfe, 16),
test_digit_sum(0xf0e, 16).</langsyntaxhighlight>
 
{{out}}
Line 3,292 ⟶ 4,066:
Sum of digits of 254 in base 16 is 29.
Sum of digits of 3854 in base 16 is 29.
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>
EnableExplicit
 
Procedure.i SumDigits(Number.q, Base)
If Number < 0 : Number = -Number : EndIf; convert negative numbers to positive
If Base < 2 : Base = 2 : EndIf ; base can't be less than 2
Protected sum = 0
While Number > 0
sum + Number % Base
Number / Base
Wend
ProcedureReturn sum
EndProcedure
If OpenConsole()
PrintN("The sums of the digits are:")
PrintN("")
PrintN("1 base 10 : " + SumDigits(1, 10))
PrintN("1234 base 10 : " + SumDigits(1234, 10))
PrintN("fe base 16 : " + SumDigits($fe, 16))
PrintN("f0e base 16 : " + SumDigits($f0e, 16))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
</lang>
 
{{out}}
<pre>
The sums of the digits are:
 
1 base 10 : 1
1234 base 10 : 10
fe base 16 : 29
f0e base 16 : 29
</pre>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">
from numpy import base_repr
 
def sumDigits(num, base=10):
return sum(int(x, base) for x in list(base_repr(num, base)))
</syntaxhighlight>
</lang>
 
or
 
<langsyntaxhighlight lang="python">def toBaseXsumDigits(num, base=10):
output = []
while num:
num, rem = divmod(num, base)
output.append(rem)
return output
 
def sumDigits(num, base=10):
if base < 2:
print ("Error: Basebase must be at least 2")
return
returnnum, sum(toBaseX = abs(num), base))0
while num >= base:
num, rem = divmod(num, base)
sum += rem
return sum + num
 
print (sumDigits(1))
print (sumDigits(12345))
print (sumDigits(-123045))
print (sumDigits(0xfe, 16))
print (sumDigits(0xf0e, 16))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,371 ⟶ 4,103:
</pre>
The following does no error checking and requires non-base 10 numbers passed as string arguments:
<syntaxhighlight lang="python">def sumDigits(num, base=10):
<lang python>
return sum(int(x, base) for x in str(num))
def sumDigits(num, base=10):
return sum([int(x, base) for x in list(str(num))])
 
print (sumDigits(1))
print (sumDigits(12345))
print (sumDigits(123045))
print (sumDigits('fe', 16))
print (sumDigits("f0e", 16))</langsyntaxhighlight>
Each digit is base converted as it's summed.
 
 
Or, as a composition of re-usable abstractions:
<langsyntaxhighlight lang="python">'''Sum digits of an integer'''
 
from functools import reduce
Line 3,494 ⟶ 4,225:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Digit sums of numbers in bases 10 and 16:
Line 3,506 ⟶ 4,237:
{{trans|Forth}}
 
<langsyntaxhighlight Quackerylang="quackery"> [ temp put 0
[ over while
swap temp share /mod
Line 3,515 ⟶ 4,246:
1234 10 digitsum echo sp
hex FE 16 digitsum echo sp
hex F0E 16 digitsum echo</langsyntaxhighlight>
 
{{out}}
Line 3,523 ⟶ 4,254:
=={{header|R}}==
{{trans|Python}}
<langsyntaxhighlight lang="rsplus">change.base <- function(n, base)
{
ret <- integer(as.integer(logb(x=n, base=base))+1L)
Line 3,549 ⟶ 4,280:
sum.digits(123045)
sum.digits(0xfe, 16)
sum.digits(0xf0e, 16)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (sum-of-digits n base (sum 0))
(if (= n 0)
Line 3,573 ⟶ 4,304:
; (1234)_10 = 10
; (254)_16 = 29
; (3854)_16 = 29</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 3,579 ⟶ 4,310:
This will handle input numbers in any base from 2 to 36.
The results are in base 10.
<syntaxhighlight lang="raku" perl6line>say Σ $_ for <1 1234 1020304 fe f0e DEADBEEF>;
 
sub Σ { [+] $^n.comb.map: { :36($_) } }</langsyntaxhighlight>
{{out}}
<pre>1
Line 3,592 ⟶ 4,323:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">
/* REXX **************************************************************
* 04.12.2012 Walter Pachl
Line 3,615 ⟶ 4,346:
End
Say res '->' right(dsum,2)
Return</langsyntaxhighlight>
{{out}}
<pre>
Line 3,633 ⟶ 4,364:
::* &nbsp; numbers may be expressed up to base 36
::* &nbsp; numbers may be any length (size)
<langsyntaxhighlight lang="rexx">/*REXX program sums the decimal digits of natural numbers in any base up to base 36.*/
parse arg z /*obtain optional argument from the CL.*/
if z='' | z="," then z= '1 1234 fe f0e +F0E -666.00 11111112222222333333344444449'
Line 3,643 ⟶ 4,374:
sumDigs: procedure; arg x; @=123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ; $=0
do k=1 to length(x); $=$ + pos( substr(x, k, 1), @); end /*k*/
return $</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 3,659 ⟶ 4,390:
 
The function makes use of REXX's &nbsp; '''parse''' &nbsp; statement
<langsyntaxhighlight lang="rexx">/*REXX program sums the decimal digits of integers expressed in base ten. */
parse arg z /*obtain optional argument from the CL.*/
if z='' | z="," then z=copies(7, 108) /*let's generate a pretty huge integer.*/
Line 3,671 ⟶ 4,402:
sumDigs: procedure; parse arg N 1 $ 2 ? /*use first decimal digit for the sum. */
do while ?\==''; parse var ? _ 2 ?; $=$+_; end /*while*/
return $</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 3,678 ⟶ 4,409:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "sum digits of 1 = " + sumDigits(1) + nl
see "sum digits of 1234 = " + sumDigits(1234) + nl
Line 3,691 ⟶ 4,422:
end
return sum
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
RPL can natively handle numbers in bases 2,8,10 or 16, but displays them according to the current base mode. For example, when you type #256d, it will be immediately turned into #100h if HEX mode is active. As there is no way to force the base mode to the base used for input, switching to string handling looks like a reasonable approach for code clarity and size. A side effect is that it can proceed with numbers in any base between 2 and 36.
{{works with|Halcyon Calc|4.2.7}}
≪ →STR → digits
≪ 0
1 digits SIZE '''FOR''' j
digits j DUP SUB NUM
'''IF''' DUP 48 ≥ OVER 57 ≤ AND
'''THEN''' 48 -
'''ELSE''' IF DUP 65 ≥ OVER 90 ≤ AND
'''THEN''' 55 -
'''ELSE''' NOT
'''END END'''
+ '''NEXT'''
≫ ≫ '<span style="color:blue">∑DIGITS</span>' STO
 
1 <span style="color:blue">∑DIGITS</span>
1234 <span style="color:blue">∑DIGITS</span>
#FEh <span style="color:blue">∑DIGITS</span>
#F0Eh <span style="color:blue">∑DIGITS</span>
{{out}}
<pre>
4: 1
3: 10
2: 29
1: 29
</pre>
 
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">def sum_digits(num, base = 10) = num.digits(base).sum
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
===Using an Iterator===
This solution creates an iterator which yields the digits of a given number using a given base and then utilizes the `sum` method which is implemented automatically on iterators.
<langsyntaxhighlight lang="rust">struct DigitIter(usize, usize);
 
impl Iterator for DigitIter {
Line 3,718 ⟶ 4,477:
fn main() {
println!("{}", DigitIter(1234,10).sum::<usize>());
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def sumDigits(x:BigInt, base:Int=10):BigInt=sumDigits(x.toString(base), base)
def sumDigits(x:String, base:Int):BigInt = x map(_.asDigit) sum</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="scala">sumDigits(0) // => 0
sumDigits(0, 2) // => 0
sumDigits(0, 16) // => 0
Line 3,742 ⟶ 4,501:
sumDigits("000999ABCXYZ", 36) // => 162
sumDigits(BigInt("12345678901234567890")) // => 90
sumDigits("12345678901234567890", 10) // => 90</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 3,750 ⟶ 4,509:
The output is the sum of the digits in the target base, displayed in base 10.
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write))
Line 3,791 ⟶ 4,550:
(test-case #b1101010101010101010101010101010101 2 10)
(test-case #b1101010101010101010101010101010101 2 1000)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,810 ⟶ 4,569:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: sumDigits (in var integer: num, in integer: base) is func
Line 3,831 ⟶ 4,590:
writeln(sumDigits(16#fe, 16));
writeln(sumDigits(16#f0e, 16));
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,846 ⟶ 4,605:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func Σ(String str, base=36) {
str.chars.map{ Num(_, base) }.sum
}
Line 3,852 ⟶ 4,611:
<1 1234 1020304 fe f0e DEADBEEF>.each { |n|
say "Σ(#{n}) = #{Σ(n)}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,861 ⟶ 4,620:
Σ(f0e) = 29
Σ(DEADBEEF) = 104
</pre>
=={{header|SQL}}==
{{works with|ORACLE 19c}}
This is not a particularly efficient solution, but it gets the job done.
 
<syntaxhighlight lang="sql">
/*
This code is an implementation of "Sum digits of an integer" in SQL ORACLE 19c
p_in_str -- input string
*/
with
function sum_digits(p_in_str in varchar2) return varchar2 is
v_in_str varchar(32767) := translate(p_in_str,'*-+','*');
v_sum integer;
begin
--
if regexp_count(v_in_str,'[0-9A-F]',1,'i')=length(v_in_str) then -- base 16
execute immediate 'select sum('||regexp_replace(v_in_str,'(\w)','to_number(''\1'',''X'')+')||'0) from dual' into v_sum;
--
elsif regexp_count(v_in_str,'[0-9]',1,'i')=length(v_in_str) then -- base 10
execute immediate 'select sum('||regexp_replace(v_in_str,'(\d)','\1+')||'0) from dual' into v_sum;
--
else
return 'Sum of digits for integer "'||p_in_str||'" not defined';
--
end if;
--
return 'Sum of digits for integer "'||p_in_str||'" = '||v_sum;
end;
 
--Test
select sum_digits('') as res from dual
union all
select sum_digits('000') as res from dual
union all
select sum_digits('-010') as res from dual
union all
select sum_digits('+010') as res from dual
union all
select sum_digits('120034') as res from dual
union all
select sum_digits('FE') as res from dual
union all
select sum_digits('f0e') as res from dual
union all
select sum_digits('öst12') as res from dual;
</syntaxhighlight>
 
{{out}}
<pre>
Sum of digits for integer "" not defined
Sum of digits for integer "000" = 0
Sum of digits for integer "-010" = 1
Sum of digits for integer "+010" = 1
Sum of digits for integer "120034" = 10
Sum of digits for integer "FE" = 29
Sum of digits for integer "f0e" = 29
Sum of digits for integer "öst12" not defined
</pre>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun sumDigits (0, _) = 0
| sumDigits (n, base) = n mod base + sumDigits (n div base, base)
 
val testInput = [(1, 10), (1234, 10), (0xfe, 16), (0xf0e, 16)]
val () = print (String.concatWith " " (map (Int.toString o sumDigits) testInput) ^ "\n")</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">function sumdigits(s) {
a = ascii(strupper(s)):-48
return(sum(a:-(a:>9)*7))
Line 3,889 ⟶ 4,706:
 
sumdigits(inbase(16, 254, 10))
29</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|4.0}}
<syntaxhighlight lang="swift">
<lang Swift>
extension String: Error {
func sumDigits(withBase base: Int) throws -> Int {
Line 3,915 ⟶ 4,732:
print(try! "fe".sumDigits(withBase: 16))
print(try! "f0e".sumDigits(withBase: 16))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,926 ⟶ 4,743:
=={{header|Tcl}}==
Supporting arbitrary bases makes this primarily a string operation.
<langsyntaxhighlight lang="tcl">proc sumDigits {num {base 10}} {
set total 0
foreach d [split $num ""] {
Line 3,940 ⟶ 4,757:
}
return $total
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts [sumDigits 1]
puts [sumDigits 12345]
puts [sumDigits 123045]
puts [sumDigits fe 16]
puts [sumDigits f0e 16]
puts [sumDigits 000999ABCXYZ 36]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,957 ⟶ 4,774:
162
</pre>
 
=={{header|TI-83 BASIC}}==
<lang TI-83b>"01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str1
Disp "SUM DIGITS OF INT"
Disp "-----------------"
Disp "ENTER NUMBER"
Input Str2
Disp "ENTER BASE"
Input B
0→R
length(Str2)→L
For(I,1,L,1)
sub(Str2,I,1)→Str3
inString(Str1,Str3)-1→S
If S≥B or S=-1:Then
Disp "ERROR:"
Disp Str3
Disp "NOT IN BASE"
Disp B
Stop
End
R+S→R
End
Disp R</lang>
 
 
=={{header|Transd}}==
<langsyntaxhighlight lang="scheme">#lang transd
 
MainModule : {
Line 4,003 ⟶ 4,795:
(tsd vvar reduce: ["(sumDigits col1)"] )
)
}</langsyntaxhighlight>{{out}}
<pre>
sum of 1:10 : 1
Line 4,012 ⟶ 4,804:
sum of 2022:3 : 6
sum of Transd:30 : 130
</pre>
 
== {{header|TypeScript}} ==
{{trans|Pascal}}
<syntaxhighlight lang="javascript">// Sum digits of an integer
 
function sumOfDigitBase(n: number, bas: number): number {
var digit = 0, sum = 0;
while (n > 0)
{
var tmp = Math.floor(n / bas);
digit = n - bas * tmp;
n = tmp;
sum += digit;
}
return sum;
}
console.log(` 1 sums to ${sumOfDigitBase(1, 10)}`);
console.log(` 1234 sums to ${sumOfDigitBase(1234, 10)}`);
console.log(` 0xfe sums to ${sumOfDigitBase(0xfe, 16)}`);
console.log(`0xf0e sums to ${sumOfDigitBase(0xf0e, 16)}`);
maxint = Number.MAX_SAFE_INTEGER;
console.log(`${maxint} (Number.MAX_SAFE_INTEGER) sums to ${sumOfDigitBase(maxint, 10)}`);
</syntaxhighlight>
{{out}}
<pre>
1 sums to 1
1234 sums to 10
0xfe sums to 29
0xf0e sums to 29
9007199254740991 (Number.MAX_SAFE_INTEGER) sums to 76
</pre>
 
=={{header|Ursa}}==
The function:
<langsyntaxhighlight lang="ursa">def sumDigits (string val, int base)
decl int ret
for (decl int i) (< i (size val)) (inc i)
Line 4,022 ⟶ 4,846:
end for
return ret
end sumDigits</langsyntaxhighlight>
 
Calling the function: (This could be done on a single line, but it's split up for clarity.)
<langsyntaxhighlight lang="ursa">out (sumDigits "1" 10) endl console
out (sumDigits "1234" 10) endl console
out (sumDigits "fe" 16) endl console
out (sumDigits "f0e" 16) endl console</langsyntaxhighlight>
{{out}}
<pre>1
Line 4,035 ⟶ 4,859:
29</pre>
 
=={{header|Visual BasicUxntal}}==
<syntaxhighlight lang="Uxntal">@sum-digits ( num* base* -: sum* )
#0000 STH2
&loop
OVR2 OVR2 DIV2k MUL2 SUB2
STH2r ADD2 STH2
DIV2k ORAk ?{ POP2 POP2 POP2 STH2r JMP2r }
SWP2 ROT2 POP2 !&loop</syntaxhighlight>
 
=={{header|V (Vlang)}}==
This version checks that only valid digits for the indicated base are passed in, exiting otherwise.
<syntaxhighlight lang="v (vlang)">
const digits = [[1, 10], [1234, 10], [0xfe, 16], [0xf0e, 16]]
 
fn main() {
<lang vb>Function sumDigits(num As Variant, base As Long) As Long
for val in digits {println(sum_digits(val[0], val[1]))}
'can handle up to base 36
}
Dim outp As Long
Dim validNums As String, tmp As Variant, x As Long, lennum As Long
'ensure num contains only valid characters
validNums = Left$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", base)
lennum = Len(num)
For L0 = lennum To 1 Step -1
x = InStr(validNums, Mid$(num, L0, 1)) - 1
If -1 = x Then Exit Function
tmp = tmp + (x * (base ^ (lennum - L0)))
Next
While tmp
outp = outp + (tmp Mod base)
tmp = tmp \ base
Wend
sumDigits = outp
End Function
 
fn sum_digits(num int, base int) int {
Sub tester()
mut sum, mut temp := 0, num
Debug.Print sumDigits(1, 10)
for temp > 0 {
Debug.Print sumDigits(1234, 10)
sum += temp % base
Debug.Print sumDigits(&HFE, 16)
temp /= base
Debug.Print sumDigits(&HF0E, 16)
}
Debug.Print sumDigits("2", 2)
return sum
End Sub</lang>
}
</syntaxhighlight>
 
{{out}} (in the debug window):
<pre>
1
10
29
11
29
20
0
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt, Conv
 
var sumDigits = Fn.new { |n, b|
Line 4,094 ⟶ 4,913:
var b = test[1]
var sum = sumDigits.call(n, b)
SystemFmt.print("%(Fmt.s($-55s in base $2d = $2d", Conv.itoa(n, b))) in base %(Fmt.d(2, b)) = %(Fmt.d(2, sum))")
}</langsyntaxhighlight>
 
{{out}}
Line 4,109 ⟶ 4,928:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, IntOut=11;
 
func SumDigits(N, Base);
Line 4,126 ⟶ 4,945:
IntOut(0, SumDigits($FE, 16)); ChOut(0, ^ );
IntOut(0, SumDigits($F0E, 16)); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,134 ⟶ 4,953:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn sum(n,b=10){
if(b==10) n.split().sum(0); // digits to list
else n.toString(b).split("").apply("toInt",b).sum(0);
}</langsyntaxhighlight>
If not base 10, convert the int into a string (in the proper base, ie
0xfe-->"fe"), blow it apart into a list of digits/characters, convert
3

edits