Sum digits of an integer: Difference between revisions

m
Missing "4" in "1234"
(Python 3, simplify)
m (Missing "4" in "1234")
 
(39 intermediate revisions by 15 users not shown)
Line 11:
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F sum_digits(=n, base)
V r = 0
Line 793 ⟶ 792:
print "f0e base 16 : "; SumDigits(0xf0e, 16)
end</syntaxhighlight>
 
==={{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}}===
Line 810 ⟶ 999:
110 END
</syntaxhighlight>
 
==={{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}}===
Line 834 ⟶ 1,102:
PRINT "f0e base 16 :"; SumDigits(&HF0E, 16)
END</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight 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</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight 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</syntaxhighlight>
 
==={{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)
DECLARE FUNCTION SumDigits% (Num AS INTEGER, NBase AS INTEGER)
 
CLS
Line 900 ⟶ 1,126:
LOOP
SumDigits% = iSum
END FUNCTION</syntaxhighlight>
</syntaxhighlight>
 
{{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}}===
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
<syntaxhighlight 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</syntaxhighlight>
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}}==
Line 1,194 ⟶ 1,541:
{{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}}==
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}}==
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}}==
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}}==
Line 1,779 ⟶ 2,374:
end program digit_sum
</syntaxhighlight>
 
=={{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|Frink}}==
Line 1,829 ⟶ 2,389:
=={{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'''
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 01.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.
 
'''Test cases'''
 
[[File:Fōrmulæ - Sum digits of an integer 02.png]]
 
[[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}}==
Line 1,929 ⟶ 2,507:
}
}</syntaxhighlight>
 
 
=={{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}}==
Line 2,331 ⟶ 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}}==
Line 2,381 ⟶ 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}}==
Line 2,490 ⟶ 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}}==
Line 2,512 ⟶ 3,200:
<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}}==
Line 3,236 ⟶ 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}}==
Line 3,323 ⟶ 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}}==
<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>
 
Line 3,719 ⟶ 4,423:
return sum
</syntaxhighlight>
 
=={{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}}==
Line 4,042 ⟶ 4,774:
162
</pre>
 
=={{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|Transd}}==
Line 4,152 ⟶ 4,859:
29</pre>
 
=={{header|Visual BasicUxntal}}==
<syntaxhighlight lang="Uxntal">@sum-digits ( num* base* -: sum* )
 
#0000 STH2
This version checks that only valid digits for the indicated base are passed in, exiting otherwise.
&loop
 
OVR2 OVR2 DIV2k MUL2 SUB2
<syntaxhighlight lang="vb">Function sumDigits(num As Variant, base As Long) As Long
'can handle up to baseSTH2r 36ADD2 STH2
DIV2k ORAk ?{ POP2 POP2 POP2 STH2r JMP2r }
Dim outp As Long
SWP2 ROT2 POP2 !&loop</syntaxhighlight>
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
10
11
20
0
</pre>
 
=={{header|V (Vlang)}}==
Line 4,220 ⟶ 4,896:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt, Conv
 
var sumDigits = Fn.new { |n, b|
Line 4,237 ⟶ 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))")
}</syntaxhighlight>
 
3

edits