Post Reply 
Tupper's 'Self-referencing' Formula
05-20-2022, 03:04 PM
Post: #5
RE: Tupper's 'Self-referencing' Formula
Hi, matalog

Instead of removing leading zeroes of quotient up-front, it may be simpler to fix afterwards.
Getting a quotient automatically generated remainder (for free), we might as well return both.

Code:
function divmod(num, den)           -- NOTE: num = string of digits
    local q, r, k = '0', 0, 2
    for i = 1, #num do
        local r2 = 10*r + (num:byte(i)-48)
        local q2 = floor(r2/den)
        q = q .. q2
        r = r2 - q2*den              -- num:sub(1,i) = q*den + r
    end
    while q:byte(k)==48 do k=k+1 end -- skip leading zeroes
    return q:sub(min(k,#q)), r       -- but, if all zeroes, keep 1 zero
end

Note that r2 does not involve mod function, thus more efficient.
If we don't care about quotient leading zeroes, after for-end loop, we can simply return q, r

lua> divmod('12345678901234567890', 111)
111222332443554665 75
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Tupper's 'Self-referencing' Formula - Albert Chan - 05-20-2022 03:04 PM



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