我正在创建一个简单的闲置游戏,在这个游戏中,你买东西,你买的每件东西的价格都会上涨。我有一个按钮,允许玩家购买最大的金额,她可以在一次点击。这可以很好地工作,但是计算总价格非常慢,因为我是在while循环中计算的。我怎么才能简化这个过程呢?
var accumulatedPrice = 0.0
var maxMultiplier = 0
while accumulatedPrice <= allMyMoney:
var assetPrice = 4.8
var priceGrowth = 1.12
priceGrowth = pow(priceGrowth, asset.currentAmount+maxMultiplier-1)
assetPrice *= priceGrowth
accumulatedPrice += assetPrice
maxMultiplier += 1我稍微简化了我的代码,它不是用任何特定的语言编写的。我实际上使用了一个大数字类来支持非常大的数字,但是数学和上面的一样。当maxMultiplier最终变高时,它会变得很慢。
发布于 2021-01-21 06:34:52
我似乎不理解这个问题。我尝试了一个64位的最大整数(9223372036854775807),它花了我2.7418136596679688e-05秒。
from time import time
import sys
all_money = sys.maxsize
asset_price = 1.8
price_growth = 1.12
next_asset_price = asset_price ** price_growth
amount = 0
start = time()
while all_money > 0:
if all_money - next_asset_price < 0:
print(f"Total: {amount}")
break
all_money -= next_asset_price
amount += 1
next_asset_price = next_asset_price ** price_growth
print(f"\nTotal runtime: {time()-start}")发布于 2021-01-22 00:53:06
对于n项目的成本总和,您有一个递归公式:
S(n) = S(n-1) + BaseCost*(k^(n-1))
可以通过提取BaseCost来简化它
BaseCost S(N)=*(1+ k^1 + k^2 + k^3 + ... +k^(n-1))BaseCost
对于这类有限几何级数,有一个公式:

因此,我们最初的求和公式可以简化为:
BaseCost S(N)=*(1-k^n)/(1-k)BaseCost
使用这个非递归公式,您可以将算法重写为简单的计算。
给定最大可用金额Smax,我们可以执行以下操作:
Smax*(1-k)/BaseCost = 1-k^n
n = log_k(1 - Smax*(1-k)/BaseCost)
我在https://docs.google.com/spreadsheets/d/1sZMpmHzcNu6NWw9HJexlIz1onOMh3DdlJYiW548xlgM/edit?usp=sharing的电子表格中测试了它
https://stackoverflow.com/questions/65818360
复制相似问题