Re: division by 7 efficiently



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.

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

How accurate does it need to be? Will 3 or 4 significant figures be
enough? If so, pick a fraction close to 1/7 whose denominator is a
power of 2.

For example, let's pick 2^16 as the denominator. 2^16 / 7 is 9362.28,
so let's pick 9362 as the numerator. Therefore, our fraction is
9362 / 2^16, and our algorithm is:

int divide_by_7 (int n)
{
return (n * 9362) >> 16;
}

A little testing (by comparing that with actual division) shows that
you get better results (for small numbers) if you round up to 9363
instead, so:

int divide_by_7 (int x)
{
return (n * 9363) >> 16;
}

A quick program I wrote shows that for integer division, this gets
the correct answer for all numbers in the range [0 .. 13109].
Maybe that is good enough.

But here's something even more interesting. If I convert 9362 to
binary, I see a sort of a pattern:

10010010010010

In fact, look at the pattern behind 2^64 / 7:

10010010010010010010010010010010010010010010010010010010010010

To me, that seems a *little* too regular to be a coincidence.

In fact, this makes a lot of sense. 1/7 is a repeating fraction in
binary. It's 0.001001001001... . And if you multiply that fraction
by 7 (which is 0b111), you get 0.111111111111..., which equals 1.0.

- Logan
.



Relevant Pages

  • Re: Old question?
    ... In seeking to eliminate comments from a valid C program, ... but it involves a division operator immediately ... is a division operator or the first character of a // comment ... int f ...
    (comp.lang.c)
  • Re: Bit-related question
    ... Subtraction is addition of a number that has been negated. ... complement signed ints, negation consists of adding one to the one's ... int main ... Copyright Microsoft Corporation 1984-2002. ...
    (microsoft.public.vc.language)
  • Re: If statement for time
    ... David Biddulph ... Times are a fraction so the INTis removing the fraction, ... The Int() rounds the time value to remove the date. ...
    (microsoft.public.excel.misc)
  • Re: Decreasing order of address within main
    ... int main ... But, from check_1, it confirms that subtraction of a constant ... Don't ignore warning messages. ... The result of subtracting two pointer values is a signed integer ...
    (comp.lang.c)
  • Re: [C] Program has a math bug
    ... Jack Klein wrote: ... > First it performs the subtraction of one double value from the other. ... > takes one parameter of type int, it must convert the result of the ... Edd, ...
    (alt.comp.lang.learn.c-cpp)