首页 > 解决方案 > 计算价格上涨的商品总价太慢

问题描述

我正在创建一个简单的闲置游戏,您可以在其中购买东西并且购买的每件商品的价格都会上涨。我有一个按钮,允许玩家单击一次即可购买最大数量。这很好用,但是计算总价非常慢,因为我是在一个 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 最终变高时,它会变慢。

标签: pythonalgorithmmathgame-development

解决方案


我似乎不明白这个问题。我已经用 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}")

推荐阅读