java factorial recursion code example
Example 1: factorial program in java without recursion
public class Tester {
static int factorial(int n) {
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
public static void main(String args[]) {
int i, fact = 1;
int number = 5;
fact = factorial(number);
System.out.println(number + "! = " + fact);
}
}
Example 2: how to make factorial in java
class fact{
static int fac(int n){
int ans =1;
for(int i=1; i<=n; i++){
ans = ans*i;
}
return ans;
}
public static void main (String[] args){
int f = 5;
System.out.println(fac(f));
}
}
Example 3: Factorial program in java
public class FactorialRecursion
{
public static void main(String[] args)
{
int factorial = 1;
int number = 6;
factorial = factorialFunction(number);
System.out.println("Factorial of " + number + " is : " + factorial);
}
static int factorialFunction(int num)
{
if(num == 0)
{
return 1;
}
else
{
return(num * factorialFunction(num - 1));
}
}
}
Example 4: recursion factorial java
public class Factorial {
public static void main(String[] args) {
int num = 6;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}