4 ms·
A glimmer of a solution: 1/3 = 0.010101... base 2. x = let x0,x1,...,xN-2,xN-1 (MSB is x0 and LSB is xN-1) Now y = x/3 = x * 1/3, where y=(y0,y1,...), so a
by femto 14y ago
A glimmer of a solution:
1/3 = 0.010101... base 2.
x = let x0,x1,...,xN-2,xN-1 (MSB is x0 and LSB is xN-1)
Now y = x/3 = x * 1/3, where y=(y0,y1,...), so a long multiplication will look something like (being sloppy about exact bit positions):
x0,x1,...,xN-2,xN-1
* 0.010101...
-------------------------
x0,x1,x2,x3,x4,x5...,xN-2,xN-1
x0,x1,x2,x3,x4,x5...,xN-2,xN-1
x0,x1,x2,x3,x4,x5...,xN-2,xN-1
Let's shorten it by grouping the bits in pairs, so BN=(b2N,b2N+1).
X0,X1,X2,X3
X0,X1,X2,X3
X0,X1,X2,X3
Y0,Y1,Y2,Y3,Y4,Y5
or:
Y0 =X0 or X0 +1
Y1=X1+X0+carry =X1+Y0 or X1+Y0+1 (extra bits of carry are in Y0)
Y2=X2+X1+X0+carry=X2+Y1 or X1+Y1+1 (extra bits of carry are in Y1)
The key is that in the above, there is only ever a single bit being carried between bit pairs, as the "01" pattern in 1/3 base 2 limits how carries propagate.
Here's a partial solution, which only works fro a few trivial cases (eg 2^N) since I haven't accounted for the possability of a single bit carry. For a full solution, maybe a conditional is required and an additonal logic operation or two to perform an increment on a pair of bits?
div3(int x)
{
int y=0;
while(x)
y ^= (x>>=2)
return(y)
}
Can anyone complete it?
Edit: formatting. Beats me how to do fixed width properly.
Edit: Oops. In the time it took me to write this qntm got there first!