# Re: integer divide by 7 trick?

Discussion in 'C++' started by yvan joffre, Jul 25, 2003.

1. ### yvan joffreGuest

I don't understand the meaning of "extra" in your code.

Why do not write just this:

unsigned int SeqDiv7(unsigned int val) {
unsigned int v=val, result=0;
while(v > 0) {
v >>= 3;
result += v;
}
return result;
}

(because
x / 7 = x / 8 + x / 64 + x / 512 + ... + x / (2^(i * 3)) + ...
)

I think it should work for any value
yvan joffre, Jul 25, 2003

2. ### Roy SmithGuest

(yvan joffre) wrote:
> Why do not write just this:
>
> unsigned int SeqDiv7(unsigned int val) {
> unsigned int v=val, result=0;
> while(v > 0) {
> v >>= 3;
> result += v;
> }
> return result;
> }

Why the intermediate variable v? Why not just use val directly in the
body of the function?
Roy Smith, Jul 25, 2003

3. ### Stewart GordonGuest

On 25/7/03 12:07 am (UK time), yvan joffre let loose these words:

> I don't understand the meaning of "extra" in your code.

The remainders after shifting, summed up modulo 7.

> Why do not write just this:

<snip>
> (because
> x / 7 = x / 8 + x / 64 + x / 512 + ... + x / (2^(i * 3)) + ...
> )
>
> I think it should work for any value

Try it and see.

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
on the 'group where everyone may benefit.
Stewart Gordon, Jul 25, 2003
4. ### Stewart GordonGuest

On 25/7/03 2:18 am (UK time), Roy Smith let loose these words:

> (yvan joffre) wrote:
>
>>Why do not write just this:
>>
>>unsigned int SeqDiv7(unsigned int val) {
>> unsigned int v=val, result=0;
>> while(v > 0) {
>> v >>= 3;
>> result += v;
>> }
>> return result;
>>}

>
>
> Why the intermediate variable v? Why not just use val directly in the
> body of the function?

Not sure. Guess that to me, val means what was actually passed into the
function, rather than some modification of it.

Speaking of which, do most compilers tend to generate the same code
either way? (g++ 3.1 (Mac OS X) is giving me the exact same except for
one byte, and they seem to take the same amount of time.)

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
on the 'group where everyone may benefit.
Stewart Gordon, Jul 25, 2003