Created
December 12, 2016 22:14
-
-
Save HaraldKorneliussen/6e27c9bfc36103b7e2dfcedd773bd4e4 to your computer and use it in GitHub Desktop.
A different way to uniquely factorize natural numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Duval's algorithm | |
function lyndonFac(str) | |
local k = 1 | |
local ret = {} | |
while k <= #str do | |
local i,j = k, k+1 | |
while j <= #str and str:sub(i,i) <= str:sub(j,j) do | |
if str:sub(i,i) == str:sub(j,j) then | |
i = i + 1 | |
else | |
i = k | |
end | |
j = j + 1 | |
end | |
while k < i + 1 do | |
local oldk = k | |
k = k + j - i | |
table.insert(ret, {oldk,k - oldk}) | |
end | |
end | |
return ret | |
end | |
function bij_to_num(str) | |
local ret = 0 | |
for i=1, #str do | |
ret = ret + (tonumber(str:sub(i,i)) + 1) * 2^(#str - i) | |
end | |
return ret | |
end | |
function num_to_bij(num) | |
local ret = "" | |
local i = 0 | |
local rem = (num + 1) % 2 | |
while num > 0 do | |
rem = (num + 1) % 2 | |
ret = "" .. rem .. ret | |
num = math.floor(num/2) - rem | |
end | |
return ret | |
end | |
-- Prints the first 50 factorizations | |
for i=1, 50 do | |
local str = num_to_bij(i) | |
for _,v in ipairs(lyndonFac(str)) do | |
io.write(bij_to_num(str:sub(v[1], v[1]+v[2] - 1)) .. " ") | |
end | |
print('') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment