int div3(int x) {
x <<= 6; // need more precise
x += x>>2; // x = x * (1+(1/2)^2)
x += x>>4; // x = x * (1+(1/2)^4)
x += x>>8; // x = x * (1+(1/2)^8)
x += x>>16; // x = x * (1+(1/2)^16)
return (x+1)>>8; // as (1-(1/2)^32) very near 1,
// we plus 1 instead of div (1-(1/2)^32)
}
although it uses +, but somebody already implements add by bitwise op
This one is the classical division algorithm in base 2:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint32_t mod3[6] = { 0,1,2,0,1,2 };
uint32_t x = 1234567; // number to divide, and remainder at the end
uint32_t y = 0; // result
int bit = 31; // current bit
printf("X=%u X/3=%u\n",x,x/3); // the '/3' is for testing
while (bit>0)
{
printf("BIT=%d X=%u Y=%u\n",bit,x,y);
// decrement bit
int h = 1; while (1) { bit ^= h; if ( bit&h ) h <<= 1; else break; }
uint32_t r = x>>bit; // current remainder in 0..5
x ^= r<<bit; // remove R bits from X
if (r >= 3) y |= 1<<bit; // new output bit
x |= mod3[r]<<bit; // new remainder inserted in X
}
printf("Y=%u\n",y);
}
I think the right answer is:
Why would I not use a basic operator to do a basic operation?
Idiotic conditions call for an idiotic solution:
If also the decimal part is needed, just declare
result
asdouble
and add to it the result offmod(number,divisor)
.Explanation of how it works
fwrite
writesnumber
bytes (number being 123456 in the example above).rewind
resets the file pointer to the front of the file.fread
reads a maximum ofnumber
"records" that aredivisor
in length from the file, and returns the number of elements it read.If you write 30 bytes then read back the file in units of 3, you get 10 "units". 30 / 3 = 10
This should work for any divisor, not only three. Currently only for unsigned, but extending it to signed should not be that difficult.
first:
then figure out how to solve x/(1 - y):
with y = 1/4:
although it uses
+
, but somebody already implements add by bitwise opThis one is the classical division algorithm in base 2:
First that I've come up with.
EDIT: Sorry, I didn't notice the tag
C
. But you can use the idea about string formatting, I guess...