Velocity Reviews > C++ > Division by 7 without using the divide operator

# Division by 7 without using the divide operator

Justin.Velazquez@gmail.com
Guest
Posts: n/a

 01-19-2007
Hello everyone,

I'm not really new to programming but my bitwise skills definately need
work.
I came across a problem I've been trying to figure out for fun. I'm
trying to write
a routine that will divide a number by 7 without using the divide
operator. I
figured how to multiply by 7 using bitwise operators ( (x << 3) - x )
but I having
a hard time trying to figure a bitwise approach to do the divide. The
closed I've
been able to come is:

((x>> 3) + x) >> 3

This works for most cases but not all. Am I approaching this problem
wrong?
is it possible to divide by 7 using bitwise operators? Any advice or
help would be
greatly appreciated.

Thanks
justin

Alf P. Steinbach
Guest
Posts: n/a

 01-19-2007
* http://www.velocityreviews.com/forums/(E-Mail Removed):
> Hello everyone,
>
> I'm not really new to programming but my bitwise skills definately need
> work.
> I came across a problem I've been trying to figure out for fun. I'm
> trying to write
> a routine that will divide a number by 7 without using the divide
> operator. I
> figured how to multiply by 7 using bitwise operators ( (x << 3) - x )
> but I having
> a hard time trying to figure a bitwise approach to do the divide. The
> closed I've
> been able to come is:
>
> ((x>> 3) + x) >> 3
>
> This works for most cases but not all. Am I approaching this problem
> wrong?
> is it possible to divide by 7 using bitwise operators? Any advice or
> help would be
> greatly appreciated.

Your draft solution can be approximated as (x/8+x)/8 = (9x//8=(9/64)x.
Since 9 decimal = 1001 binary, and since 1/64 = 0.000001 binary, that
is essentially the same as multiplying x by 1001*0.000001 = 0.001001
binary, wheras 1/7 = 0.0010010010010010... binary. Perhaps you can see
a pattern both in that expansion and in your first draft solution?

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?