Pin It

How to perform Factorial caching in a Java application ?.

A simple program to demonstrate how to do Factorial caching in Java

package com.hubberspot.example;

import java.util.Scanner;

public class FactorialCaching {

 // an array of long values to cache the factorial values
 public static long[] factorial = new long[21];

 // a loop counter that counts till end of number for 
 // which we want to calculate factorial
 public static int fact = 0;

 // static initializer block, the block of executes as 
 // soon as the class is loaded into the memory for 
 // the first time. Here it initializes value of first
 // element of array to be 1 as factorial of 1 is 1
 static { 
  factorial[0] = 1; 
 }     

 // method where the logic for factorial 
 // calculations goes. It takes a argument which
 // is the number passed for which we want to 
 // calculate the factorial
 public static long factorial(int x) {

  // fact goes from zero to number-1 for which we want to 
  // calculate the factorial
  while(fact < x) {

   // applying formula as 3! = 3 * 2!
   factorial[fact + 1] = factorial[fact] * (fact + 1);

   // increment the fact for next value
   fact++;
  }

  // return the result
  return factorial[x];
 }

 public static void main(String[] args) {

  // Create a Scanner object to read input from console
  Scanner scanner = new Scanner(System.in);

  // prompt the user to enter the number for which factorial
  // is to be calculated
  System.out.println("Enter the number for which you " +
    "want to calculate factorial -  ");

  // prompting the user to enter number between 0 to 20 
  System.out.println("Note : \"The number should range " +
    "from 0 to 20\"");

  // store the number entered into number variable
  int number = scanner.nextInt();

  // For the first time call factorial method to store
  // values into the array of calculated factorials
  long result = FactorialCaching.factorial(number);

  // the result displayed on the console
  System.out.println("The factorial of "+ number +" : " + result);

  System.out.println();
  System.out.println("Enter the another number for which you " +
    "want to calculate factorial -  ");

  // prompting the user to enter number between 0 to 20 
  System.out.println("Note : \"The number should range " +
    "from 0 to "+number+"\"");

  // store the number entered into number variable
  number = scanner.nextInt();

  // After first call to factorial method next time 
  // we just access the factorial by accessing the 
  // long array through index
  System.out.println("The factorial after caching is done : " 
    + FactorialCaching.factorial[number]);

 }

}


Output of the program : 


 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot