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

Asked

Viewed 70 times

1

Why my accumulator variable does not 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)

1 answer

2


I won’t touch the structure of the code much, but I will write in a way that is readable and in a more correct style. The problem is the for. The numbers placed there appear to be random. The first must be the beginning of the loop, so 1 is correct. The second indicates the end of the loop, so it should be 9 and not 2. The third is how much he should jump on each passage through the loop, so it should be 1. So:

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)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.