Devise an algorithm for writing any positive base ten integer in NegaDuodecimal number system.
How about negative base ten integers?
As an extra challenge, extend this to writing base ten positive rational numbers in NegaDuodecimal number system.
Rather than use floor or ceiling on the quotiont, find the remainder first, in the usual quotient-and-remainder method of converting to another base from decimal. If the remainder is negative, add the divisor (that is, the base to which you're converting), so that it's positive. From there, subtract the remainder (now positive in any instance) from the dividend so that the result is divisible by the base and becomes the new dividend:
clc
base=-12;
for n= -15:18
n2=n;
nega=[];
while abs(n2)>0
r=mod(n2,base);
if r<0
r=r+abs(base);
end
q=(n2-r)/(base);
nega=[nega r];
n2=q;
end
disp([n flip(nega)])
end
decimal digits of base -12
------- ------------------
-20 2 4
-19 2 5
-18 2 6
-17 2 7
-16 2 8
-15 2 9
-14 2 10
-13 2 11
-12 1 0
-11 1 1
-10 1 2
-9 1 3
-8 1 4
-7 1 5
-6 1 6
-5 1 7
-4 1 8
-3 1 9
-2 1 10
-1 1 11
0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 1 11 0
13 1 11 1
14 1 11 2
15 1 11 3
16 1 11 4
17 1 11 5
18 1 11 6
19 1 11 7
20 1 11 8
As seen above this same algorithm works for both positive and negative integers. A special case is zero: use 0 for any base.
As for fractional values, I don't know what to do.
|
Posted by Charlie
on 2022-09-23 11:21:18 |