Tuesday, April 22, 2008

Factorial Algorithm

The factorial of a number is the product of all positive integers less than or equal to it. e.g. the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.

While conducting a Java interview, I like to ask my candidates to write an algorithm to calculate the factorial of a number. This is one of my favourite questions because it gives me an insight into their thinking process. It is also one of the questions that I was asked at Merrill Lynch, in my first interview out of university. (I got it right)

I am surprised at how the majority of people cannot answer this question, or get anywhere close to it. C'mon, you can do it using recursion or loop-iteration; its not that difficult! If you can't count backwards, do it forwards - its the same thing.

Here is a simple solution:

5 comments:

  1. Anonymous3:46 PM

    Come on now Fahd, you aren't meant to be giving away your interview questions - you'll loose your edge!!

    ReplyDelete
  2. Anonymous3:42 PM

    hi,
    theres actually a small error above:

    # //recursion
    # public int recursiveFactorial(int n)
    # {
    # if (n == 0)
    # return 1 ;
    # else
    # return n * factorial(n-1) ;
    # }

    last line should be
    return n * recursiveFactorial(n-1) ;

    thanks,
    ak

    ReplyDelete
  3. you're right, amit. Thanks for spotting the error. Will fix it.

    ReplyDelete
  4. Anonymous11:12 PM

    Theres another problem with your code.

    int only suports to 2,147,483,647 + range.

    so you can only calculate to about 12! with that code.

    even with long type you cannot go to 100!

    ReplyDelete

Note: Only a member of this blog may post a comment.