Lua 最小公倍数程序内存不足。

这是我编写的一个 Lua 程序,用于找到两个数的最小公倍数。当我运行它时,它像预期的那样要求输入两个数字,但当它尝试通过函数运行它们时,便会耗尽内存。

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)
点赞
用户1190388
用户1190388

这个错误是因为 io.read 调用导致的。从 PiL 中得知:

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

因此,你的值 n1n2 在函数中被作为字符串传递,从而永远不会满足 until aL == buntil 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-21 19:37:10