12-19-2020, 10:03 AM
Since b+b may overflow, I tend to stick to idiv3:
function idiv3(a,b) -- assumed b > 0
local q, c = floor(a/b), b+1
a, b = a%b - a%c, q%c -- a-b = [2-2c, c-2]
if a==b or a==b-c then return q end
return q-1
end
But I rewrite it as
function idiv3(a,b) -- assumed b > 0
local q, c = floor(a/b), b+1
a, b = a%b, a%c
b = (q-c+b)%c
if a==b then return q end
return q-1
end
Turning it into RPN, the latter can be done using only the stack as I need 1 less variable.
(it's part of a Quotient-and-remainder routine a=q*b+r, and I return b in L, q in X and r in Y)
Werner
function idiv3(a,b) -- assumed b > 0
local q, c = floor(a/b), b+1
a, b = a%b - a%c, q%c -- a-b = [2-2c, c-2]
if a==b or a==b-c then return q end
return q-1
end
But I rewrite it as
function idiv3(a,b) -- assumed b > 0
local q, c = floor(a/b), b+1
a, b = a%b, a%c
b = (q-c+b)%c
if a==b then return q end
return q-1
end
Turning it into RPN, the latter can be done using only the stack as I need 1 less variable.
(it's part of a Quotient-and-remainder routine a=q*b+r, and I return b in L, q in X and r in Y)
Werner