Divide a number by 3 without using *, /, +,
How would you divide a number by 3 without using * , / , + , - , % , operators?
The number may be signed or unsigned.
This is a simple function which performs the desired operation. But it requires the + operator, so all you have left to do is to add the values with bit-operators:
// replaces the + operator
int add(int x, int y)
{
while (x) {
int t = (x & y) << 1;
y ^= x;
x = t;
}
return y;
}
int divideby3 (int num)
{
int sum = 0;
while (num > 3) {
sum = add(num >> 2, sum);
num = add(num >> 2, num & 3);
}
if (num == 3)
sum = add(sum, 1);
return sum;
}
As Jim commented this works because:
n = 4 * a + b n / 3 = a + (a + b) / 3 So sum += a, n = a + b , and iterate
When a == 0 (n < 4) , sum += floor(n / 3); ie 1, if n == 3, else 0
Idiotic conditions call for an idiotic solution:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp=fopen("temp.dat","w+b");
int number=12346;
int divisor=3;
char * buf = calloc(number,1);
fwrite(buf,number,1,fp);
rewind(fp);
int result=fread(buf,divisor,number,fp);
printf("%d / %d = %d", number, divisor, result);
free(buf);
fclose(fp);
return 0;
}
If also the decimal part is needed, just declare result as double and add to it the result of fmod(number,divisor) .
Explanation of how it works
fwrite writes number bytes (number being 123456 in the example above). rewind resets the file pointer to the front of the file. fread reads a maximum of number "records" that are divisor 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
log(pow(exp(number),0.33333333333333333333)) /* :-) */
链接地址: http://www.djcxy.com/p/6346.html
上一篇: 双行军立方体表
下一篇: 将数字除以3而不使用*,/,+,
