Factor numbers from 1 to 9, cumulative variable printing wrong number

0

Why does not my accumulator variable print 6?

acum=1
n1=6
for i=1,2,3 do
    if n1%2==0 then acum=acum*2 n1=n1/2  
        elseif  n1%3==0 then acum=acum*3 n1=n1/3
            elseif  n1%5==0 then acum=acum*5 n1=n1/5
                elseif n1%7==0 then acum=acum*7 n1=n1/7 
    end
    if n1==1 then break end
end

print(acum)
    
asked by anonymous 04.12.2016 / 02:38

1 answer

1

I'm not going to mess around with the code structure, but I'll write in a way that is readable and in a more correct style. The problem is for . The numbers placed there seem to be random. The first must be the start of the loop, so 1 is correct. The second indicates the end of the loop, so it should be 9 instead of 2. The third is how much it should jump at each pass through the loop, so it should be 1. Thus:

local acum = 1
local n1 = 6
for i = 1, 9, 1 do
    if n1 % 2 == 0 then
        acum = acum * 2
        n1 = n1 / 2
    elseif n1 % 3 == 0 then
        acum = acum * 3
        n1 = n1 / 3
    elseif n1 % 5 == 0 then
        acum = acum * 5
        n1 = n1 / 5
    elseif n1 % 7 == 0 then
        acum = acum * 7
        n1 = n1 / 7 
    end
    if n1 == 1 then break end
end
print(acum)

See running on ideone .

    
04.12.2016 / 09:59