Tricks:
- If a number
den
is a power of2
thenden&den-1
is0
. - When the
denominator
is power of2
,denominator-1
hasx
number of1s
as lsb where2x = den
. - The lsb digits are the mod result and the msb digits are the div result.
mod result = 3
1011 //n = 11, den = 4
div result = 2
int mod(n, den):
if isPowerOf2(den-1):
return n & (den-1)
else
return n % den
int div(n, den):
if isPowerOf2(den-1):
return n & (~(den-1)) >> countOf1Bits(den-1)
else
return n / den
int countOf1Bits(n)
count = 0
while n > 0:
n &= n-1
count++
return count
bool isPowerOf2(den):
return den > 0 && (den & (den-1)) == 0
example:
n = 11
den = 4
mod(11, 4):
1011 //11
0100 // 4
0011 // 4-1
0011 //11 & (4-1) = 3 = 11 % 4
div(11, 4):
1011 //11
0100 // 4
0011 // 4-1
1100 // ~(4-1)
1000 //11 & (~(4-1))
0011 // countOf1Bits(4-1) = 2
0010 //11 & (~(4-1)) >> countOf1Bits(4-1) = 2 = 11 / 4
[Hat tip to CTCI]
No comments:
Post a Comment