Negative base numbers: Difference between revisions

Line 396:
 
=={{header|J}}==
The j languages has builtin base and antibase verbs defined over the full complex realm. However, antibase produces negative digits. Additional coding required for antibase. Negative base works as is once the literal is converted back to a base 10 vector.
 
 
Model: python version.
Python and j divmod for negative divisor agree but for transposition.
 
<pre>
>>> # python divmod
>>> [divmod(i, -2) for i in (2, 3, 4, 5)]
[(-1, 0), (-2, -1), (-2, 0), (-3, -1)]
>>>
</pre>
 
<pre>
NB. j divmod
divmod =: <.@:%`(|~)`:0
2 3 4 5 divmod _2
_1 _2 _2 _3
0 _1 0 _1
</pre>
 
 
 
<pre>
NB. Use: BASE encode_neg_base INTEGER
NB. Output: literal
neg_antibase =: dyad define
b =. x
n =. y
if. 0 = n do. '0' return. end.
out =. i.0
while. n do.
'n rem' =. n divmod b
if. rem < 0 do.
n =. >: n
rem =. rem - b
end.
out =. out , rem
end.
(|. out) { _10 |. AlphaNum_j_
)
 
NB. use: BASE neg_base LITERAL
NB. output: integer
neg_base =: #. (_10 |. AlphaNum_j_)&i.
 
NB. neg_antibase test passes
_2 _3 _10 neg_antibase&> 10 146 15
11110
21102
195
 
NB. in j we would write the tautology
(":&.>11110 21102 195) -: _2 _3 _10 neg_antibase&.> 10 146 15
1
 
NB. expressive numeric notation
NB. we can write the numbers in arbitrary base
NB. The digit characters are limited to [0-9a-z]
 
_2b11110 _3b21102 _10b195
10 146 15
 
 
NB. neg_base test passes
 
_2 neg_base '11110'
10
 
_3 neg_base '21102'
146
_10 neg_base '195'
15
 
 
[ EXTRA_CREDIT =: _63 neg_base&> ;: 'J j apl APL Iverson'
19 45 139718 38136 1069471233985
_63 neg_antibase&> EXTRA_CREDIT
J
j
apl
APL
Iverson
 
=={{header|Java}}==
Anonymous user