Codechef : Problem name " Small Factorial " solution in C#
==========================Solution============================
using System;
public class Test
{
public static void Main()
{
int t=Convert.ToInt32(Console.ReadLine());
for(int i=0;i<t;i++){
int X=Convert.ToInt32(Console.ReadLine());
Console.WriteLine((int)factProgram(X));
}
}
public static int factProgram(int n){
if(n==1){return 1;}
if(n==0){return 1;}
return factProgram(n-1)*n;
}
}
=============================Explanation============================
We have solved this problem using recursion
Recursion is function calling himself and break out un till the valid condition is not reached.
In this problem I have created a method factProgram, which takes an input integer. and it is returning product of input number and factProgram(input number - 1)., so this function is calling itself with the smaller number and if check call stack we can trace current value of the number which has been input.
Condition to break is after number has been passes we are checking if it becomes 1 or 0, then it will return the complete computation.
Comments
Post a Comment