The most efficient javascript algorithm for calculating the amount if the amount was to double every day

Give N days with doubling the amount of money every day, is this the most effective way to accomplish this?

Day one: they give you $ .5.
Second day: they give you twice the amount for one day 1 dollar, now you have 1.5 US dollars. Day three: you are given twice as much as two days 2 dollars, and now you have 3.5 dollars USA 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); } 

It is just purely ademic. Don't really try to shave cycles or anything else.

Thanks.

EDIT:

alt text

+4
source share
4 answers

The code you provided does not execute what the description says.

If the initial amount is a, then the amount you receive on the i-th day is a * 2 ^ i , and the amount after n days is the amount from 0 to n.

Simplification , we get:

 a * (2 ^ (n+1) - 1) 

No cycle required.

+9
source

If I understand the problem correctly, it's just a simple geometric progression , starting at 0.5 and doubling the cost every day. The sum is nothing more than the sum of n members of this series, which is equal to:

 a * (r^n - 1) ------------- r - 1 

Here a = 0.5, r = 2 ; substituting the formula:

 0.5 * (2^n - 1) 

Or, which is the same thing, in JavaScript:

 return 0.5 * (Math.pow(2, days) - 1); 
+7
source

What about:

 return (Math.pow(2.0, days + 1) - 1) * initial_amount; 

No iteration required. If you received the initial batch .5, then after 1 day you will have (2 ^ 2-1) * .5 == 1.5, after 2 days you will have (2 ^ 3-1) *. 5 == 3.5, etc.

Note that this assumes initial_amount on day 0, not 1. If you intend to start the first day, just remove + 1 from the expression.

Also note: if you are talking about money, the formula looks strange. Money usually doubles daily, including the initial amount. So, on the 1st day you will have 1 dollar, on the 2nd day 2 dollars, day 3 $ 4, etc.

0
source

Is it correct?

 return parseInt(Array(days).join('1'), 2) + 0.5 
0
source

All Articles