Priklad 1 - Bez rekurzie [w/o Recursion]:
public static int Factorial(int x) { if (x < 0) { throw new ArgumentException("The argument is negative "); } int result = 1; for (int i = 2; i <= x; i++) { result *= i; } return result; }
Priklad 2 - S rekurziou [ w/ Recursion]:
public static int Factorial(int x) { if (x < 0) { throw new ArgumentException("The argument is negative "); } if (x==0 || x==1) { return 1; } return x * Factorial(x - 1); }
Priklad 3 - IEnumerable:
public static IEnumerable<int> Factorial(int x) { if (x < 0) { throw new ArgumentException("The argument is negative "); } if (x == 0) { yield return 1; } int startIndex = 1; while (startIndex <= x) { yield return startIndex; startIndex++; } }
Priklad 4 = LINQ:
public static int Factorial(int x) { return Enumerable.Range(1, x).Aggregate((i, r) => r * i); }