Negative base numbers: Difference between revisions

→‎{{header|REXX}}: fixed handling of zero.
m (→‎{{header|Sidef}}: replaced ".pairs" with ".kv")
(→‎{{header|REXX}}: fixed handling of zero.)
Line 230:
n= 15; b=-10; nb=nBase(n,b); say right(n, 20) @ right(b, 3) '────►' nb ok()
n=-15; b=-10; nb=nBase(n,b); say right(n, 20) @ right(b, 3) '────►' nb ok()
n= 0; b= -5; nb=nBase(n,b); say right(n, 20) @ right(b, 3) '────►' nb ok()
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
nBase: procedure; parse arg x,r; $= $= /*obtain args; $ is the integer result.*/
do while x\==0 /*keep processing while X isn't zero.*/
z=x//r; x=x%r /*calculate remainder; calculate int ÷.*/
if z<0 then do; z=z-r /*subtract a negative R from Z ◄──┐ */
x=x+1 /*bump X by one. │ */
end end /* Funny "add" ►───┘ */
$=z || $ /*prepend new digit (numeral) to result*/
end /*while*/
return word($ 0,1) /*when $ is NULL, then return a zero.*/
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
ok: ?=; if pBase(nb,b)\=n then ?= ' ◄──error in negative base calculation'; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
pBase: procedure; parse arg x,r; $=0; p=0 /*obtain args; $ is the integer result.*/
L=length(x); do j=L by -1 for L /*process each of the numerals in X. */
_=substr(x, j, 1) /*obtain a numeral of the X number. */
Line 256 ⟶ 257:
15 converted to base -10 ────► 195
-15 converted to base -10 ────► 25
0 converted to base -5 ────► 0
</pre>