我的朋友约翰喜欢去看电影。他可以在系统A和系统B之间进行选择。
系统A :每次买票(15美元)
系统B :每次都要买一张卡(500美元) 买票的价格是他为前一票价支付的价格的0.90倍。
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便宜。
功能影片有3个参数:卡片(卡片的价格),门票(门票的正常价格),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;
};
答案 0 :(得分:0)
您的退出条件可能永远不会发生在您引用的代码中,因为您将WithCardPrice
增加了ticket
平方。这样,WithTicketPrice
不会只是开始降低,而是始终会更小,给定ticket > 1.0
和card > 1.0
。
我想你想写
WithCardPrice = WithCardPrice + ticket * (1 + i * perc);
或类似的东西?