首页 > 解决方案 > 由于执行超时,在javascript中编写更快的循环函数

问题描述

我的朋友约翰喜欢去看电影。他可以在系统 A 和系统 B 之间进行选择。

系统A:每次买票(15美元)

系统B:买一张卡(500美元),每次买一张票,票价是前一张票价的0.90倍。

示例:如果约翰去电影院 3 次:

    System A : 15 * 3 = 45
    System B : 500 + 15 * 0.90 + (15 * 0.90) * 0.90 + (15 * 0.90 * 0.90) * 0.90 
    ( = 536.5849999999999, no rounding for each ticket)

约翰想知道他必须去电影院多少次,这样系统 B 的最终结果,当四舍五入到下一美元时,会比系统 A 便宜。

函数 movie 有 3 个参数:card(卡的价格)、ticket(门票的正常价格)、perc(他为前一张门票支付的部分)并返回第一个 n 使得

ceil(price of System B) < price of System A.

更多示例:

movie(500, 15, 0.9) should return 43 
    (with card the total price is 634, with tickets 645)
movie(100, 10, 0.95) should return 24 
    (with card the total price is 235, with tickets 240)

我写了这段代码,但我在网页上收到了超时消息。有人可以建议我如何编写比这更快的代码吗?

   function movie(card, ticket, perc) {
var WithTicketPrice = 0;
var WithCardPrice = card+ticket*perc;
var Counter = 1;

while (WithTicketPrice <= Math.ceil(WithCardPrice)) {

      WithTicketPrice = WithTicketPrice + ticket;

      WithCardPrice = WithCardPrice + (ticket*Math.pow(perc, Counter)*perc);
      Counter++;

    }

  return Counter-1;

};

标签: javascriptloopsruntime-error

解决方案


从您引用的代码开始,您的退出标准可能永远不会发生,因为您增加了WithCardPrice平方ticket。这样,在给定和WithTicketPrice的情况下,它不仅会开始变小,而且会一直变小。ticket > 1.0card > 1.0

我猜你想写

WithCardPrice = WithCardPrice + ticket * (1 + i * perc);

或类似的东西?


推荐阅读