Post Reply 
Tupper's 'Self-referencing' Formula
05-20-2022, 08:46 PM
Post: #6
RE: Tupper's 'Self-referencing' Formula
(05-20-2022 03:04 PM)Albert Chan Wrote:  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

You refer to q2 as a string when you use
Code:
q = q .. q2
but you refer to it as a number when you use
Code:
local q2 = floor(r2/den)
. Is it a string or a number?
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Tupper's 'Self-referencing' Formula - matalog - 05-20-2022 08:46 PM



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