division by 7 efficiently ???

Bart Ogryczak B.Ogryczak at gmail.com
Fri Feb 2 07:03:58 EST 2007


On Feb 1, 3:42 am, krypto.wiz... at gmail.com wrote:
> How to divide a number by 7 efficiently without using - or / operator.
> We can use the bit operators. I was thinking about bit shift operator
> but I don't know the correct answer.

It´s quiet simple. x ==  8*(x/8) + x%8, so x == 7*(x/8) + (x/8 + x%8)
x/8 == x>>3, x%8 == x&7
And there you have it, function rounds upwards for numbers not
divisible by 7. Gotta change int(x>0) to int(x>3) to round normally,
or int(x>6) to round downwards.

def d7(x):
	if(x>>3 == 0): return int(x>0)
	return (x>>3)+d7((x>>3)+(x&7))




More information about the Python-list mailing list