Post Reply 
(42, all flavours) Integer Division - how?
12-18-2020, 12:08 AM (This post was last modified: 12-19-2020 12:56 AM by Albert Chan.)
Post: #39
RE: (42, all flavours) Integer Division - how?
remainder() based idiv is very elegant.
PHP Code:
function idiv6(ab)    -- assumed b 0
    local r 
a/b
    local q 
floor(r)
    if 
== and remainder(ab) < 0 then q=q-1 end
    
return q
end 

Above is similar to this (6a version possibly faster, only tried to get remainder sign)
PHP Code:
function idiv6a(ab)   -- assumed b 0
    local r 
a/b
    local q 
floor(r)
    if 
~= r then return q end
    r 
% (b+b)
    
local R and or r-b
    local h 
0.5*b    -- halfway
    
if or == h then return q end
    
return 1
end 

All the code for mod/half-way test is the last if line.

R < h:

if residual is less than half of b, q had rounded-down. For floor divide, no need for correction.

r == h:

if residual is half of b, q (because of round-to-even) is even.
But, r also guaranteed even q -> no need for correction.

Update: slightly faster version 6b, removed R, and r shifted, with range = [-2h, 2h)

PHP Code:
function idiv6b(ab)   -- assumed b 0
    local r 
a/b
    local q 
floor(r)
    if 
~= r then return q end
    r 
% (b+b) - b
    local h 
0.5*b     -- halfway
    
if <= -or (and >= 0then return q end
    
return 1
end 
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: (42, all flavours) Integer Division - how? - Albert Chan - 12-18-2020 12:08 AM



User(s) browsing this thread: 12 Guest(s)