Factorial program in C#
Factorial of n is the product of all positive descending integers. Example: 4! = 4*3*2*1 = 24
Factorial is the most commonly asked programming question. Let’s look at the solutions:
Using while loop:
The simplest solution is to calculate factorial using the while loop . Time complexity of this solution O(n).
1 2 3 4 5 6 7 8 9 10 | public static int Factorial(int n) { int a = 1; while (n > 1) { a *= n--; } return a; } |
Using Recursion
1 2 3 4 5 6 7 | static int FactorialRec(int n) { if (n == 0) return 1; return n*FactorialRec(n-1); } |