Re: division by 7 efficiently




On Thu, 31 Jan 2007 krypto.wizard@xxxxxxxxx wrote:

Last month I appeared for an interview with EA sports and they asked
me this question.

How would you divide a number by 7 without using division operator ?

I did by doing a subtraction and keeping a counter that kept a tab on
how many times I subtracted.

Wrong. Well, technically you /could/ do division that way --- you
could call it the "caveman" method, since maybe a particularly dumb
caveman might do that with pebbles --- but it would be hopelessly
slow. Namely, it's O(2**n) for an n-digit number.

Later, the EA sport guy told me that of course there are can be better
technique by using bit operator.

Yes. If you had a compiler handy, and wanted to impress the interviewer
with your knowledge of other people's knowledge of mathematics, you
could also do it this way:

int bar(int x)
{
int y = ((long long)x * -1840700269) >> 32;
return ((x + y) >> 2) + (x < 0);
}


Since 7 has a binary representation 111, my guess is that a left shift
operation of 3 bits should give the answer, but I couldn't get it to
work.

Left-shifting a value by 3 multiplies it by 2**3 = 8. That's not the
right constant, or the right operation.

Any comments ?

Yes; you're not ready to program games for a living yet.

-Arthur
.



Relevant Pages

  • Re: division by 7
    ... How would you divide a number by 7 without using division operator? ... I did by doing a subtraction and keeping a counter that kept a tab on ... (that is actually a solution to there question if that was the exact ...
    (sci.math)
  • Re: division by 7
    ... How would you divide a number by 7 without using division operator? ... I did by doing a subtraction and keeping a counter that kept a tab on ... So to divide by 7: shift left 3, then again, then again, etc. ...
    (sci.math)
  • Re: division by 7 without using division operator
    ... How would you divide a number by 7 without using division operator? ... I did by doing a subtraction and keeping a counter that kept a tab on ... a: the required multiplication ...
    (comp.lang.c)
  • Re: division by 7 efficiently
    ... How would you divide a number by 7 without using division operator? ... I did by doing a subtraction and keeping a counter that kept a tab on ... and will probably fail within 3 bits of maximum int. ...
    (comp.programming)
  • Re: Is Oil Running Low
    ... If you project the usage by subtraction and divide into the projected reserves still left you get 3. ...
    (sci.energy)