Home c# How to calculate factorial in c #?

How to calculate factorial in c #?

Author

Date

Category

What is the easiest way to calculate the factorial in c # ???


Answer 1, authority 100%

public static long Fact (long n) {
 if (n == 0)
  return 1;
 else
  return n * Fact (n - 1);
}
long num = Fact (5); /// 120

Answer 2, authority 99%

C # is a multi-paradigm language, so it can have a few simple ways to calculate factorial.

The

Imperative way is the classic for :

// connect the System.Runtime.Numerics assembly for the BigInteger type
using System.Numerics;
public BigInteger Factorial (int n)
{
  var factorial = new BigInteger (1);
  for (int i = 1; i & lt; = n; i ++)
    factorial * = i;
  return factorial;
}

Here we have used the BigInteger type, which allows us to compute factorials of arbitrary size.

The recursive method has already been given in the answers here.

Another functional way of calculating based on LINQ capabilities can be given:

public BigInteger Factorial (int n)
{
  return Enumerable.Range (1, n)
           .Aggregate (new BigInteger (1), (f, i) = & gt; f * i);
}

Essentially the same is done here as in the first example.


Answer 3

Also one of the possible solutions:

public static double Factorial (double a)
{
  if (a% 1 == 0)
  {
    if (a == 0) return 1;
    if (a & gt; 0)
    {
      int _ = 1;
      for (int i = 1; i & lt; = a; i ++)
      {
        _ * = i;
      }
      return _;
    }
  }
  return double.NaN;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions