简体   繁体   中英

Probability calculator in c#

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM