Velocity Reviews > C++ > Re: integer divide by 7 trick?

# Re: integer divide by 7 trick?

yvan joffre
Guest
Posts: n/a

 07-24-2003
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

Roy Smith
Guest
Posts: n/a

 07-25-2003
http://www.velocityreviews.com/forums/(E-Mail Removed) (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?

Stewart Gordon
Guest
Posts: n/a

 07-25-2003
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
Guest
Posts: n/a

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

> (E-Mail Removed) (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.