GeeksforGeeks » Interview Questions

Divisible by 3. If yes find the quotient

(7 posts)
  • Started 7 months ago by mystry
  • Latest reply from Guddu Sharma
  1. mystry
    Member
    Posted 7 months ago #

    You are given with Binary Representation of a Number.
    Using only BitWise operation (No *, / , %) Find if the Number is divisible by 3.
    If yes, then return the quotient. else return -1.

  2. aks
    guest
    Posted 7 months ago #

    start from 0th bit and count the number of 1s alternatively i.e. 0th bit, 2ndbit, 4th bit....
    now start from 1st bit and count the number of 1s alternatively i.e. 1st bit, 3rdbit, 5th bit....
    if these two counts are equal,then num is div by 3

  3. RangaRao
    Member
    Posted 7 months ago #

    A good one..

  4. ashish
    guest
    Posted 7 months ago #

    @aks:
    whats logic behind this??

  5. ashish
    guest
    Posted 7 months ago #

    @aks:
    whats logic behind this??

  6. techcoder
    Member
    Posted 7 months ago #

    @ aks and all above
    wrong solution
    counter Ex 21
    binary reprsenetation 00010101
    number of set even bits =3
    number of set odd bits =0
    both the counts are not equal but 21 is divisible by 3

    correct solution
    if(number of set bits at even position - number of set bits at odd position) is divisible by 3
    then the number is divisible by 3.

  7. mystry
    Member
    Posted 7 months ago #

    @All:
    Guys thanks for the solution to find whether the number is divisible by 3 or not. (I knew this solution already :P )

    My question is: If the number is divisible by 3 then what is quotient.
    ex 21 / 3 =7.
    now as 21 is divisible by 3 then the output should be 7. otherwise the output should be Indivisible or -1.

  8. Guddu Sharma
    Member
    Posted 1 month ago #

    Use DFA concept.
    state=0;

    while(bits are remaining)//move from MSB to LSB
    {
    	if(bit==0)
    	{
    		if(state==0)
    			state=0;
    		else if(state==1)
    			state=2;
    		else if(state==2)
    			state=1;
    	}
    	else if(bit==1)
    	{
    		if(state==0)
    			state=1;
    		else if(state==1)
    			state=0;
    		else if(state==2)
    			state=2;
    	}
    } 
    
    if(state==0)
    	Number is divisible by 3;
    else
    	Not divisible by 3;

Reply

You must log in to post.

RSS feed for this topic