-2

I've got a programing problem.

I've been trying to do something like a probability calculator in c#, for that I need a certain type of factorial. I know how to program factorial, but I need

sum of all the factorials from zero to some given number.

Suppose the input number is some constant r, what I want is:

0! + 1! +2! + ... + (r-1)! + r!

This is what I've got so far, but still does not work:

double a, j, k = 1, sum = 1, l = 1;

for (a = 1; a <= f; a ++)
{
    for (j = 1; j <= a; j++)
    {
        l = k * j;
    }

    sum = sum + l;
}

Console.WriteLine(sum);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Where's the factorial calculation? `k` is always 1 so at the end of the loop `l` is simply equal to `a`. Split your code into functions, make sure the `factorial` function works and only then try to use it for other calculations – Panagiotis Kanavos Feb 03 '21 at 21:32
  • I don't think your code is doing what you expect just based on certain factors like k=1. You multiple k by j, but k never changes from 1. f doesn't exist. This needs code needs some work before you'll be ready to even ask for help with the problem at hand. – Carson Feb 03 '21 at 21:35
  • 1
    https://stackoverflow.com/questions/29027000/c-sharp-to-calculate-factorial – Ctznkane525 Feb 03 '21 at 21:40

1 Answers1

1

One simple for loop is enough. Since factorial grows fast, let's use BigInteger type; however, if you want, you can change all BigInteger into double:

using System.Numerics;

...

// 0! + 1! + 2! + ... + value!
public static BigInteger MyFunc(int value) {
  if (value < 0)
    throw new ArgumentOutOfRangeException(nameof(value));

  BigInteger result = 1;
  BigInteger factorial = 1;

  for (int i = 1; i <= value; ++i) 
    result += (factorial *= i);

  return result;
}

Demo:

using System.Linq;

...

int[] tests = new int[] {
  0, 1, 2, 3, 4, 5, 6, 7
};

string report = string.Join(Environment.NewLine, 
  tests.Select(x => $"{x} => {MyFunc(x),4}"));

Console.WriteLine(report);

Outcome:

0 =>    1
1 =>    2
2 =>    4
3 =>   10
4 =>   34
5 =>  154
6 =>  874
7 => 5914
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215