Give N days, with money amount doubling each day, is this the most efficient way to accomplish 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With