Divide a number by 3 without using *, /, +, -, % operators
How would you divide a number by 3 without using *
, /
, +
, -
, %
, operators?
The number may be signed or unsigned.
Solution 1:
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 iterateWhen
a == 0 (n < 4)
,sum += floor(n / 3);
i.e. 1,if n == 3, else 0
Solution 2:
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
- The
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
Solution 3:
log(pow(exp(number),0.33333333333333333333)) /* :-) */
Solution 4:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int num = 1234567;
int den = 3;
div_t r = div(num,den); // div() is a standard C function.
printf("%d\n", r.quot);
return 0;
}