-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Factorial.cs
38 lines (32 loc) · 1.13 KB
/
Factorial.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Numerics;
namespace Algorithms.Numeric;
/// <summary>
/// The factorial of a positive integer n, denoted by n!,
/// is the product of all positive integers less than or equal to n.
/// </summary>
public static class Factorial
{
/// <summary>
/// Calculates factorial of a integer number.
/// </summary>
/// <param name="inputNum">Integer Input number.</param>
/// <returns>Factorial of integer input number.</returns>
public static BigInteger Calculate(int inputNum)
{
// Convert integer input to BigInteger
BigInteger num = new BigInteger(inputNum);
// Don't calculate factorial if input is a negative number.
if (BigInteger.Compare(num, BigInteger.Zero) < 0)
{
throw new ArgumentException("Only for num >= 0");
}
// Factorial of numbers greater than 0.
BigInteger result = BigInteger.One;
for (BigInteger i = BigInteger.One; BigInteger.Compare(i, num) <= 0; i = BigInteger.Add(i, BigInteger.One))
{
result = BigInteger.Multiply(result, i);
}
return result;
}
}