how to implement the % operator for unsigned integer?

4

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
lua
modulo
asked on Stack Overflow Oct 31, 2018 by hongyu xiao • edited Oct 31, 2018 by Egor Skriptunoff

1 Answer

2
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
answered on Stack Overflow Oct 31, 2018 by Egor Skriptunoff

User contributions licensed under CC BY-SA 3.0