title: Why is factorial calculation much faster in Haskell than in Java
body: <p>One of the programming problems I have come across involves calculation of factorials  of large numbers (of numbers up to 10^5). I have seen a simple Haskell code which goes like this</p>
  
  <pre><code>factorial :: (Eq x, Num x) =&gt; x -&gt; x
  factorial 0 = 1
  factorial a = a * factorial (a - 1)
  </code></pre>
  
  <p>which implicitly handles the huge numbers and somehow runs faster even without any caching that is involved in the code. </p>
  
  <p>When I tried to solve the problem using Java, I had to use BigInteger to hold the huge numbers and also use iterative version of factorial</p>
  
  <pre><code>public static BigInteger factorialIterative(int n)
  {
          if(n == 0 || n == 1) return BigInteger.valueOf(1);
          BigInteger f = BigInteger.valueOf(1);
          for(int i = 1 ; i &lt;= n ;i++)
              f = f.multiply(BigInteger.valueOf(i));
          return f;
  }
  </code></pre>
  
  <p>The above code exceeded the set time limit of execution for the program . I also tried the cached recursive version of factorial</p>
  
  <pre><code>public static BigInteger factorial(int n)
  {
       if(cache[n] != null) 
           return cache[n];
       else if(n == 0) 
           return new BigInteger("1");
       else {
           cache[n] = n* factorial(n - 1);
           return cache[n]; 
       }
  }          
  </code></pre>
  
  <p>which gave me an out of memory error (probably due to recursion). </p>
  
  <p>My Question is , why are functional programming languages like Haskell better in handling these sorts of problems involving huge numbers? (despite no obvious caching). Is there a way I can make the java code run as fast as the Haskell code?</p>