Reputation: 239
How to implement the % operator or function for lua's unsigned integer? I thought of using type cast to float, but precision is a problem.
function ModU(a, b)
if b == 0 then return a end
if a == 0 then return 0 end
if b < 0 then
if a < 0 then
if a < b then return b-a
else return a
end
else
return a
end
else
if a > 0 then return math.tointeger(a % b)
else
i = ModU(x & 0x7fffffff + 1, b)
j = ModU(2^31 - 1, b)
return ModU(i + j, b)
end
end
end
Upvotes: 4
Views: 217
Reputation: 974
function unsigned_mod(x, y)
return y<=x and x<0 and x-y or y<0 and x or ((x>>1)%y*2+(x&1)-y)%y
end
Upvotes: 2