loops - Lua Least Common Multiple Program Not Enough Memory -
this lua program wrote find least common multiple of 2 numbers. when run it, asks 2 numbers intended, when tries run them through function, runs out of memory.
function lcm(a,b) alist={} blist={} c=0 if a<b repeat c=c+1 alist[c]=a*c blist[c]=b*c al=table.getn(alist) until al==b else if a>b 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] 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)
the bug arises because of io.read
call. pil
the read function reads strings current input file.
thus, values n1
, n2
passed strings inside function , hence, never causing until al == b
or until bl == a
satisfied 1 of them string number. solve problem, can 1 of following:
pass
"*number"
control argument:n1 = io.read( "*number" ) n2 = io.read( "*number" )
cast
a
,b
numbers:function lcm(a,b) a, b = tonumber(a), tonumber(b)
Comments
Post a Comment