Home Misc Divide a number by 3 without using *, /, +, -, % operators

# Divide a number by 3 without using *, /, +, -, % operators

0 comment

Question:

How can you divide a number by 3 without using *, /, +, – % operator?

Input: 48
Output: 16

The method below implements the method using bit-wise operators.

//a function to add 2 numbers without using +
{
int a, b;
do
{
a = x & y;
b = x ^ y;
x = a << 1;
y = b;
} while (a);

return b;
}

int divideby3(int num)
{
int sum = 0;

while (num > 3)
{
sum = add(num >> 2, sum);
num = add(num >> 2, num & 3);
}

if (num == 3)

return sum;
}

//the main function
int main(void)
{
printf("Enter a number:- ");
int num;
scanf("%d",&num);

printf("The number divided by 3 is:- %d",divideby3(num));

return 0;
}


For example if your number is 10 then convert to binary
10 =>00001010
if 10 > 3 then shift the binary number 2 bits
Now num will be 00000010 ie, 2
Now sum will be 2
num = (shift the number by 2 bits)+(number BITWISE AND 3)
num = 2+2

Now the number will be 4 then, 4>3 => true so loop will be repeated
4=>00000100 then shift the binary number 2 bits
Now sum=2+1 ie, sum=3   (this value is returned)
num=(shift the number(00000100) by 2 bits)+(number BITWISE AND 3)
num=1+0
ie remainder=1

#### You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More