# Computing the addition chain of an integer

Trying to remove all numbers that aren’t in the addition chain for the number n from a table with numbers 1 to 7.

Here’s the code I wrote: (I know it doesn’t support numbers >15 but just trying to get it to work with smaller numbers)

``````local numbers = {1,2,3,4,5,6,7}

local n = 6
local n2 = 0

if math.ceil(n) == n then -- Check if n is an integer
n2 = n/2 -- Divide n by 2 if it is
else
error(n .. ' is not an integer')
end

if math.ceil(n2) == n2 then -- Check if n2 is an integer (finds if n is odd or even)
for i = 1, #numbers, -1 do -- if n is even, remove all numbers from the table except for n2
if numbers[i] ~= n2 then
table.remove(numbers, i)
end
end
print(numbers)
else
for i = 1, #numbers, -1 do -- if n is odd, remove all numbers except n-0.5 or 1 from the table
if numbers[i] ~= n2-0.5 or 1 then
table.remove(numbers,i)
end
end
print(numbers)
end
``````

This SHOULD print out: (because 3+3 = 6)

``````{
 = 3
}
``````

``````{
 = 2,
 = 3,
 = 5,
 = 7
}
``````

Solved. Needed to change

``````for i = 1, #numbers, -1 do
``````

to

``````for i = #numbers, 1, -1 do
``````

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.