1

This is a Lua program I wrote to find the least common multiple of two numbers. When I run it, it asks for two numbers as intended, but when it tries to run them through the function, it runs out of memory.

function lcm(a,b)
    aList={}
    bList={}
    c=0
        if a<b then
            repeat
                c=c+1
                aList[c]=a*c
                bList[c]=b*c
                aL=table.getn(aList)
            until aL==b
            else
            if a>b then
                repeat
                    c=c+1
                    aList[c]=a*c
                    bList[c]=b*c
                    bL=table.getn(bList)
                until bL==a
            end
        end
    e=1
    repeat
        d=1
        repeat
            if aList[e]==bList[d] then
                f=aList[e]
                return f
            end
        d=d+1
        until d==table.getn(aList)
    e=e+1
    until e==table.getn(bList)
end

n1=io.read()
n2=io.read()
ans=lcm(n1,n2)
print(ans)
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • 3
    Using `repeat ... until` to iterate over lists is very non-idiomatic – Eric Jul 21 '13 at 19:32
  • Also, you've got an off by one error somewhere - `lcm(3, 5)` returns nil. As does `lcm(3, 3)` – Eric Jul 21 '13 at 19:44
  • [Here's](https://gist.github.com/eric-wieser/9923fe959cf2d50e4f8a) the same (incorrect) algorithm, written idiomatically – Eric Jul 21 '13 at 19:48

1 Answers1

4

The bug arises because of the io.read call. From PiL

The read function reads strings from the current input file.

Thus, your values n1 and n2 are passed as strings inside the function and hence, never causing the until aL == b or until bL == a to be satisfied as one of them is a string another a number. To solve this problem, you can one of the following:

  1. Pass "*number" as control argument:

    n1 = io.read( "*number" )
    n2 = io.read( "*number" )
    
  2. Cast a and b to numbers:

    function lcm(a,b)
        a, b = tonumber(a), tonumber(b)
    
hjpotter92
  • 78,589
  • 36
  • 144
  • 183