javascript - 由于执行超时,在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;
};
解决方案
从您引用的代码开始,您的退出标准可能永远不会发生,因为您增加了WithCardPrice
平方ticket
。这样,在给定和WithTicketPrice
的情况下,它不仅会开始变小,而且会一直变小。ticket > 1.0
card > 1.0
我猜你想写
WithCardPrice = WithCardPrice + ticket * (1 + i * perc);
或类似的东西?
推荐阅读
- android - 如何使用`androidx`和`navgation architecture`运行android仪器测试?
- regex - PCRE 条件语句与预期不匹配
- django - 在vue js中刷新页面时保持用户会话登录
- r - 在 R 中创建了一个 for 循环到(ggplot)具有一个对应列(x)的多列,当它看到一个 0 时如何停止并移动到下一列?
- javascript - 我在这段代码的逻辑流程上遇到了问题,导致输出不正确
- python - Tensorflow/Numpy:如何修复此错误,以便获得 2 个目标预测
- python - C 语言中的所有 Python 模块(如“数学”和“时间”)在哪里?
- javascript - 如何从mongo数据库中完全删除文档的子文档
- sql - 尝试用 JOIN 替换 Cross Apply
- android - 最佳实践:Android KeyStore 使用哪些 AES 设置