Anonymous user
Negative base numbers: Difference between revisions
m
→{{header|REXX}}: simplified some code.
(Added Go) |
m (→{{header|REXX}}: simplified some code.) |
||
Line 822:
$=z || $ /*prepend new digit (numeral) to result*/
end /*while*/
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
ok: ?=; if pBase(nb, b)\=n then ?=' ◄──error in negative base calculation'; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
pBase: procedure; parse arg x,r;
if r<-10 | r>-2 then do; say 'base' r "must be in range: -2 ───► -10"; exit 13; end
L=length(x); do j=L by -1 for L /*process each of the numerals in X. */
Line 833:
end /*j*/ /* [↓] process the number "bottom-up".*/
return $</lang>
<pre>
10 converted to base -2 ────► 11110
Line 856:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
nBase: procedure; parse arg x,r,,$ /*get args; $ will be integer result. */▼
parse arg $; m=length(!); L=length(x); p=0
▲ !='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz /*+-!éáµ' /*sym*/
if r<-m | r>-2 then do; say 'base' r "must be in range: -2 ───► -"m; exit 13; end
return
do while x\==0 /*keep processing while X isn't zero.*/▼
/*──────────────────────────────────────────────────────────────────────────────────────*/
do while x\==0 /*keep processing
z=x//r; x=
if z<0 then do;
end /*while*/
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
ok:
/*──────────────────────────────────────────────────────────────────────────────────────*/
pBase: procedure;
▲ do j=L by -1
v=pos( substr(x,j,1), !) - 1 /*use base R for the numeral's value.*/
▲ v=pos(substr(x,j,1),!) -1 /*use base R for the numeral's value.*/
▲ $=$ + v * r**p; p=p+1 /*add it to $ (result); bump power by 1*/
return $</lang>
<pre>
10 converted to base -2 ────► 11110
|