Most efficient javascript algorithm to calc total if amount were to double each day
Give N days, with money amount doubling each day, is this the most efficient way to ac开发者_运维知识库complish this?
Day one: you are given $.5.
Day two: you are given twice the amount as day one $1, now you have $1.5 Day three: you are given twice the amount as day two $2 and now you have $3.5 And so on.function calcit3()
{
var cur_total = .5;
var prev_total = 0;
var days = 20;
for ( z = 1; z < days; z++ )
{
cur_total = cur_total * 2;
prev_total = cur_total;
}
return (cur_total + prev_total);
}
This is just purely acedemic. Not really trying to shave cycles or anything.
Thanks.
EDIT:
The code you've provided doesn't do what the description says it should.
If the initial amount is a then the amount you get on the i th day is a * 2 ^ i
, and the sum after n days is the sum of that from 0 to n.
Simplifying, we get:
a * (2 ^ (n+1) - 1)
No looping necessary.
If I understand the problem correctly, it's just a simple geometric progression starting with 0.5 and doubling in value each day. The total is nothing but the sum to n
terms of this series, which is:
a * (r^n - 1)
-------------
r - 1
Here a = 0.5, r = 2
; substituting yields the formula:
0.5 * (2^n - 1)
Or equivalently in JavaScript:
return 0.5 * (Math.pow(2, days) - 1);
Is this correct?
return parseInt(Array(days).join('1'), 2) + 0.5
How about:
return (Math.pow(2.0, days + 1) - 1) * initial_amount;
No iteration necessary. Given an initial_amount of .5, after 1 day, you'll have (2^2-1) * .5 == 1.5, after 2 days you'll have (2^3-1)*.5 == 3.5, etc.
Note, this assumes initial_amount on day 0, not 1. If you're intent on having day 1 be the start, just remove the + 1
from the expression.
Also note, if you're talking about money, the formula is kinda odd. Money would usually double daily, including the initial amount. So on day 1, you'd have $1, on day 2 $2, day 3 $4, etc.
精彩评论