title: Program Factorial in Java with a lookup table
body: <p>In an effort to improve my programming I am trying out this problem in Java. I have looked everywhere for an elegant solution and cant find it.</p>
  
  <blockquote>
    <p>Write a program which takes a single argument, computes the factorial and prints the 
    value on the screen.Also the program must be interactive instead of terminating after
    each computation and that it uses a table of previous values to improve the performance.</p>
  </blockquote>
  
  <p><strong>How do I make it so that in the method calls it checks if it has already computed the factorial for a value? Any other improvements to this code to make it more readable or efficient are also appreciated.</strong></p>
  
  <p>This is what I have written so far.</p>
  
  <pre><code>public static void main(String[] args) {
      int input = 0;
      Scanner reader = new Scanner(System.in);
  
      HashMap cache = new HashMap();
  
      while(1 == 1){
          do{
              try {
                  System.out.println("Enter the number you would like to factor");
                  input = reader.nextInt();
              } catch (InputMismatchException e){
                  reader.next();
              }
          } while(input &lt;= 0);
  
          if(cache.get(input) != null){
              System.out.println("Found in cache");
              System.out.println(input + "! = " + cache.get(input));
          } 
          else {
              cache.put(input, factorialRecursively(input));
              System.out.println(input + "! = " + factorialRecursively(input));
          }
  
      }   
  
  }       
  
  public static int factorialIteratively(int a) throws InputMismatchException {
      int temp = 1;
      while(a &gt; 0){
          temp = temp * a;
          a--;
      }
      return temp;
  }
  
  public static int factorialRecursively(int a) throws InputMismatchException{
      if (a == 1){
          return 1;
      }
      else {
          return a * factorialRecursively(a-1);
      }
  }
  </code></pre>