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)
4

1 回答 1

4

由于io.read调用而出现错误。来自PiL

read 函数从当前输入文件中读取字符串。

因此,您的值n1n2作为函数内部的字符串传递,因此,永远不会满足until aL == bor until bL == a,因为其中一个是字符串,另一个是数字。要解决此问题,您可以执行以下操作之一:

  1. "*number"作为控制参数传递:

    n1 = io.read( "*number" )
    n2 = io.read( "*number" )
    
  2. 演员表ab号码:

    function lcm(a,b)
        a, b = tonumber(a), tonumber(b)
    
于 2013-07-21T19:37:10.907 回答