## 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:

1. Anonymous3:46 PM

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

2. 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

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

4. Anonymous9:31 AM

Now do you worried about that in the game do not had enough aion kina to play the game, now you can not worried, my friend told me a website, in here you can buy a lot aion online kina and only spend a little money, do not hesitate, it was really, in here we had much aion gold, we can sure that you will get the cheap aion kina, quick to come here to buy aion kina.

Now do you worried about that in the game do not had enough aion kina to play the game, now you can not worried, my friend told me a website, in here you can buy a lot aion online kina and only spend a little money, do not hesitate, it was really, in here we had much aion gold, we can sure that you will get the cheap aion kina, quick to come here to buy aion kina.

5. 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!

6. Anonymous2:55 PM

thanks for sharing this site. you can download lots of ebook from here

http://feboook.blogspot.com