Recursion Factorial
Source: Hacker Rank
Recursive Method for Calculating Factorial
factorial(N)=1, if N<=1
=N x factorial(N-1) otherwise
Task
Write a factorial function that takes a positive integer, N as a parameter and prints the result of N!(N factorial).
Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0.
Input Format
A single integer, N (the argument to pass to factorial).
Constraints
2 <= N <= 12
Your submission must contain a recursive function named factorial.
Output Format
Print a single integer denoting N!
Sample Input
3
Sample Output
6
Explanation
Consider the following steps:
1. factorial(3) = 3 x factorial(2)
2. factorial(2) = 3 x factorial(1)
3. factorial(1) = 1
From steps 2 and 3, we can say factorial(2) = 2 x 1 = 2; then when we apply the value from factorial(2) to step 1, we get factorial(3)=3 x 2 x 1 = 6. Thus, we print 6 as our answer.
My solution:
C#:
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 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecursionFactorial { class Program { static int factorial(int n) { int result; //base case if (n == 1) return 1; else return n * factorial(n-1); } static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); int result = factorial(n); Console.WriteLine(result); Console.ReadKey(); } } } |