如何解决Lua中的Euler#12项目?

时间:2016-01-30 10:32:54

标签: lua factors

好的,这是另一个欧拉问题。 我已经开始通过解决Euler项目问题​​来学习Lua并且被困在Euler problem 12上。

在我看来非常简单,我不明白为什么我的结果不正确? 到目前为止,这是我的解决方案:

-- return triangular number of the specified number
function get_tri_num(num)
  local n = 0
  for i=1, num do
    n = n + i
  end
  return n
end

-- return all factors of the specifeid number
function factors(num)
  local factors = {}
  for i=1, num/2 do
    if num%i == 0 then
      factors[#factors+1] = i
    end
  end
  factors[#factors+1] = num
  return factors
end

-- get the first triangle number with >500 divisors
function euler12()
  local n = 0
  local trinum = 1
  while true do
    n = n + 7
    trinum = get_tri_num(n)
    if #factors(trinum) > 500 then break end
  end
  print(trinum, n)
end

euler12()

这个问题是计算密集型的,至少我解决它的方式,所以我使用luajit

time luajit euler12.lua 
103672800   14399

real    3m14.971s
user    3m15.033s
sys 0m0.000s

首先,我在问题描述中提供的玩具示例中尝试此解决方案。将euler12()行改为if #factors(trinum) > 5 then break end,我得到:

28  7

这与问题示例中显示的结果相对应。

其次,在我看到玩具示例正常工作后,我运行euler12() >500条件。根据我的解决方案,答案是 103672800 ,是的,如果我单独检查此结果的除数的数量是> 500:

print(#factors(103672800))
648

但是...

enter image description here

1 个答案:

答案 0 :(得分:2)

问题在于:

while true do
  n = n + 7

为什么n每次增加7?这没有意义,将其更改为1,您就可以得到正确答案。

然而,表现仍然不佳。有几个地方可以改进:

  • 每次调用函数get_tri_num时,它都在计算中 从头开始,这没有必要。

  • 您不需要数字因子,您只需要数字 数字因素,为什么要返回factors中的表?

  • for i=1, num/2 do没有必要。迭代到平方根 num足以获得多少因素。

有关同样的问题,请参阅my code

相关问题