-3

I would like to sum the given factorials numbers in javascript

'1! + 2! + 3! + ... + n!'
Arunprasanth K V
  • 20,733
  • 8
  • 41
  • 71
angular
  • 553
  • 2
  • 7
  • 17
  • I dont know how can write this programme.please help – angular Jun 03 '16 at 04:21
  • I'd first learn some basics and look into functions and loops. Then I'd look into how to compute the factorial of a number. http://eloquentjavascript.net can help with functions and loops, https://www.google.com with the rest. – Felix Kling Jun 03 '16 at 04:25
  • 2
    While you are at it trying looking what dynamic programming is to speed up the computation. – Derek 朕會功夫 Jun 03 '16 at 04:25

2 Answers2

0

You may use factorial function : Iterative function:

function sFact(num)
{
    var rval=1;
    for (var i = 2; i <= num; i++)
        rval = rval * i;
    return rval;
}

Recursive

function rFact(num)
{
    if (num === 0)
      { return 1; }
    else
      { return num * rFact( num - 1 ); }
}

I copied these function from this link. Now what can you do is.

Suppose n value is 6.

  var n = 6;
    var sum = 0;
    for(var i=1;i<=n;i++)
    {
       sum = sum + rFact(i);//Here you can use one of factorial funciton. I am using recursive function
    }

document.print("The answer is "+ sum );
Community
  • 1
  • 1
CodeLover
  • 271
  • 1
  • 3
  • 14
  • While it's certainly great that you want to help, I'd recommend to avoid low quality questions. Also, copying other answers is no-go. – Felix Kling Jun 03 '16 at 04:32
  • Sure @Felix. I appreciate your recommendation. – CodeLover Jun 03 '16 at 04:33
  • @FelixKling i copied and mentioned as well. – CodeLover Jun 03 '16 at 04:34
  • I know... still not great. Just link to the answer if it is a part of yours. E.g. "See [link] for computing the factorial.". It only makes sense to quote if the other answer contains a lot of unrelated information or if you are linking to an external site. – Felix Kling Jun 03 '16 at 04:36
0

The naïve solution would be to actually calculate every factorial and add them together, which has a complexity of O(n²). However, if you're clever, you can design an algorithm that solves the same problem with a complexity of O(n). Take a look at the pattern of the following example that calculates the sum of the factorials of 1 through 4.

1!+2!+3!+4! =
1+1*2+1*2*3+1*2*3*4

Notice how you're reusing results from previous calculations multiple times? This can be taken advantage of. You can calculate the sum of all the factorials up to n with a program something like this.

function sumFactorials(n) {
    var sum = 0;
    var prod = 1;
    for(var i=1; i<=n; i++) {
        prod *= i;
        sum += prod;
    }
    return sum;
}
kamoroso94
  • 1,713
  • 1
  • 16
  • 19