我正在执行一个非常密集的过程,可以将其拆分为多个coroutine
s,但是在它们中,只要获得正确的结果,就需要将其添加到变量中。目前,Lua似乎在为每个线程重置我要添加的变量,这给了我错误的结果。
我已经做了很多环顾四周的工作,但是还没有发现其他类似的问题。
s=0
function calc(x,n)
print(x,n)
for a=x,n,1 do
for b=a+1,n-1,1 do
if is_coprime(a,b,false) then
c=math.sqrt((a^2)+(b^2))
if c<=b or c>n then break; end
if is_coprime(a,b,c) then
s=s+1
break
end
end
end
end
end
function main(n)
local t=0
for i=1,n,n*.1 do
co=coroutine.create(calc)
coroutine.resume(co,i,n)
end
for _,v in ipairs(s) do
t=t+1
end
return t
end
感谢@NicolBolas的评论,我将协程抛弃了,只是使用较小的缓冲区循环了所有程序。
function calc(x,n)
local t={}
for a=x,n,1 do
for b=a+1,a^10,1 do
if is_coprime(a,b,false) then
c=math.sqrt((a^2)+(b^2))
if c<=b or c>n then break; end
if is_coprime(a,b,c) then
print(a,b,c)
t[tostring(a)..' '..tostring(b)..' '..tostring(c)]=true
break
end
end
end
end
return t
end
function main(n)
local t,s=0,{}
for i=1,n,n*.1 do
for k,v in pairs(calc(i,n)) do
if s[k]==nil then
s[k]=true
t=t+1
end
end
end
return t
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句