Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient javascript algorithm to calc total if amount were to double each day

Tags:

javascript

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:

alt text

like image 787
evets Avatar asked Dec 05 '22 00:12

evets


2 Answers

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.

like image 57
Anon. Avatar answered Dec 07 '22 23:12

Anon.


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);
like image 26
casablanca Avatar answered Dec 07 '22 23:12

casablanca