Factorials are very simple things. They're just products, indicated by an exclamation mark. For instance, "four factorial" is written as "4!" and means 1×2×3×4 = 24. In general, n! ("enn factorial") means the product of all the whole numbers from 1 to n; that is, n! = 1×2×3×...×n.
The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion.
public class FactorialRecursion {
public static void main(String[] args) {
int n=5;
System.out.println(fact(n));
}
public static int fact(int n)
{
if(n<=1)
return 1;
else
return n*fact(n-1);
}
}
The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion.
public static int factorial(int N) { if (N == 1) return 1;
else return N * factorial(N-1); }
public class FactorialRecursion {
public static void main(String[] args) {
int n=5;
System.out.println(fact(n));
}
public static int fact(int n)
{
if(n<=1)
return 1;
else
return n*fact(n-1);
}
}
Tags:
Basic