Sum digits of an integer: Difference between revisions

m
Missing "4" in "1234"
m (Missing "4" in "1234")
 
(21 intermediate revisions by 9 users not shown)
Line 11:
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F sum_digits(=n, base)
V r = 0
Line 843 ⟶ 842:
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}}===
Line 877 ⟶ 890:
 
end</syntaxhighlight>
{{out| Output}}<pre>
number: 1234567
base: 10
sum of digits in base 10: 28
</pre>
 
==={{header|FreeBASIC}}===
Line 912 ⟶ 930:
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}}===
Line 955 ⟶ 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}}===
Line 968 ⟶ 1,038:
70 GOTO 40
80 PRINT "ITS DIGIT SUM:",U
90 STOP</syntaxhighlight>
</syntaxhighlight>
{{out}}
<pre>ENTER A NUMBER:-12321
<pre>
ITS DIGIT SUM: 9</pre>
ENTER A NUMBER:-12321
ITS DIGIT SUM: 9
</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">EnableExplicit
EnableExplicit
 
Procedure.i SumDigits(Number.q, Base)
Line 1,002 ⟶ 1,068:
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf</syntaxhighlight>
</syntaxhighlight>
 
{{out}}
<pre>
Line 1,043 ⟶ 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 1,063 ⟶ 1,126:
LOOP
SumDigits% = iSum
END FUNCTION</syntaxhighlight>
</syntaxhighlight>
 
{{out}}
<pre>
Line 1,092 ⟶ 1,153:
print "fe base 16 : "; SumDigits(hexdec("FE"), 16)
print "f0e base 16 : "; SumDigits(hexdec("F0E"), 16)
end</syntaxhighlight>
{{out}}
<pre>Same as BASIC256 entry.</pre>
 
==={{header|TI-83 BASIC}}===
Line 1,159 ⟶ 1,217:
PRINT "f0e base 16 :"; SumDigits(3854, 16) !0xf0e
END</syntaxhighlight>
 
 
==={{header|Visual Basic}}===
 
This version checks that only valid digits for the indicated base are passed in, exiting otherwise.
 
Line 1,191 ⟶ 1,247:
Debug.Print sumDigits("2", 2)
End Sub</syntaxhighlight>
 
{{out}} (in the debug window):
<pre>
Line 1,200 ⟶ 1,255:
0
</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="yabasicvb">sub SumDigits(number, nBase)
if number < 0 then number = -number : fi
if nBase < 2 then nBase = 2 : fi
Line 1,457 ⟶ 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,710 ⟶ 1,811:
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 2,137 ⟶ 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 2,237 ⟶ 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 4,574 ⟶ 4,858:
29
29</pre>
 
=={{header|Uxntal}}==
<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)}}==
Line 4,603 ⟶ 4,896:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt, Conv
 
var sumDigits = Fn.new { |n, b|
Line 4,620 ⟶ 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