divide a number by 3

Discuss the object oriented programming concepts and discuss the errors and issues related to C++

divide a number by 3

New postby rose123 on Mon May 07, 2007 7:58 pm

hi
How to divide a number by 3 without using any of these operators (%,/,
*) you can use other operator

Regards
rose123
rose123
Active
Active
 
Posts: 51
Joined: Sun Apr 01, 2007 11:12 am


Divide a number by 3 without using any of operators (%,/,*)

New postby kalaid on Tue May 08, 2007 10:49 am

Following program will also divide the number by 3:
Code: Select all
int divideby3 (int num)
{
  int sum = 0;
  while (num > 3) {
        sum += num >> 2;
                num = (num >> 2) + (num & 3);
  }
  if (num == 3) ++sum;
  return sum;

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
num=(shift the number(00000100) by 2 bits)+(number BITWISE AND 3)
num=1+0
ie remainder=1
kalaid
Enthusiast
Enthusiast
 
Posts: 216
Joined: Mon Jan 08, 2007 5:39 pm
Location: coimbatore


Return to C++

Who is online

Users browsing this forum: No registered users and 1 guest


cron