如何将此循环转换为高效的数学表达式

我花了大约一个小时,太受到一件事情的影响无法弄清楚。这个循环可以按预期工作,但是代价是性能。尝试找出这个表达式以去除循环

lua

local rebirthPrice= 50000000
local currentRebirth = 1

local calculatePrice = function(user,num)
    local defaultPrice = rebirthPrice*currentRebirth
    local endPrice = 0

    --
    for index = 1,num-1 do
        endPrice += rebirthPrice*(currentRebirth+index)
    end

    endPrice += defaultPrice
    --
    return endPrice
end

print(calculatePrice(nil, 1))

--[[
    当当前重生等级为1时,
    重生一次应该花费defaultPrice
    两次应该花费1.5亿
    三次应该是3亿等
--]]
点赞
用户380384
用户380384

在数学中有一个求和规则,对于i=1..nΣ(i) = n*(n+1)/2

在你的情况下,i=1..num-1

endPrice = defaultPrice + Σ(rebirthPrice*(currentRebirth+i))
         = defaultPrice + Σ(rebirthPrice*currentRebirth) + Σ(rebirthPrice*i)
         = defaultPrice + (num-1)*(rebirthPrice*currentRebirth) + rebirthPrice*Σ(i)
         = defaultPrice + (num-1)*(rebirthPrice*currentRebirth) + rebirthPrice*(num-1)*num/2
2021-01-01 17:11:07
用户1630618
用户1630618

为了直观起见,让我们应用分配律并将您的循环重写为:

for index = 1,num-1 do
    endPrice += rebirthPrice * currentRebirth
    endPrice += rebirthPrice * index
end

由于循环运行了 $n-1$ 次,因此第一部分向 endPrice 添加了 rebirthPrice * currentRebirth * (n-1)

最后,您将 defaultPrice 添加到了 endPrice 中,而 defaultPrice 正是 rebirthPrice * currentRebirth。将其添加到循环中贡献的 rebirthPrice * currentRebirth * (n-1),得到:

endPrice = rebirthPrice * currentRebirth * n

到目前为止,其次方程在循环中对终值产生什么影响?

endPrice += rebirthPrice * index

index 递增:1、2、3、…、num-1

因此,endPrice 增加了 rebirthPrice * (1 + 2 + ... + num - 1)

有一个公式:

1 + 2 + ... + x = x(x + 1)/2

应用该公式,循环中的第二个方程式产生了以下贡献(取 $x = num-1$):

endPrice += rebirthPrice * (num - 1)(num - 1 + 1)/2

简化:

endPrice += rebirthPrice * num * (num - 1)/2

因此,将这些内容综合起来:

endPrice = rebirthPrice * currentRebirth * num + rebirthPrice * num * (num - 1)/2
         = rebirthPrice(currentRebirth * num + num * (num - 1)/2)
         = rebirthPrice * num * (currentRebirth + (num - 1)/2)
         = rebirthPrice * num * (2 * currentRebirth + num - 1) / 2
2021-01-01 17:14:22