Factorial of number in Java - CodeByAkram

Factorial of number in Java


Factorial of number in Java.

Factorial of number is product of a number and the following number below it.
For Example: 
Factorial of 6

6! =6 * 5 * 4 * 3 * 2 * 1 = 720.

Factorial of 5 
5! = 5 * 4 * 3 * 2 * 1 = 120.

Note: The value of 0! is 1


Algorithm

Now Lets talk about the algorithm for printing Factorial of a Number in java.

There ae 3 ways of finding Factorial of number,


  1. Recursive Implementation
  2. Iterative Implementation
  3. Using BigInteger for Large values.
Check Recursive Implementation Program flow below.



Java Program to Print Factorial of a number using Recursion.

package codebyakram;
 
import java.math.BigInteger;
 
public class FindFactorialOfNumber {
 
 public static void main(String[] args) {
  System.out.println(factRecursive(5));
  System.out.println(factIterative(5));
  System.out.println(factorialForLargeNumbers(5));
 }
 
 //Recursive Implementation
 private static int factRecursive(int num){
  if(num < 0){
   return -1;
  }
 
  if(num == 1 || num == 0){
   return 1;
  }
  num = num * factRecursive(num-1);
  return num; 
 }
 
 //Iterative Implementation
 private static int factIterative(int num){
  if(num < 0){
   return -1;
  }
 
  int fact = 1;
  for (int i = 1; i <= num; i++) {
   fact *= i;
  }
  return fact;
 }
 
 //Using BigInteger for Large values
 public static String factorialForLargeNumbers(int num) {
  if(num < 0){
   return "-1";
  }
   
  BigInteger fact = new BigInteger("1");
   
  for (int i = 1; i <= num; i++) {
   fact = fact.multiply(new BigInteger(String.valueOf(i)));
  }
  return fact.toString();
 }
 
}

No comments:

Post a Comment