Day#2 of Java Programming Practice: Return Factorial of a number
Taking a first look at this problem, I decided to skip it as it seemed very simple. Then I thought, may be instead of using the simple for-loop, I will try writing it using recursive function. This did turn out to be a challenge for me because I had always avoided learning and practicing recursions. This is the final version of the program I wrote and its output:
Taking the advice, I started working on updating my program to make use of BigInteger. This again was a challenge for me as I was not familiar with the availability and usage of BigInteger methods and fields. This is the final version of the program and its output.
"Recursive solution is a bad example
Writing a recursive factorial function is a mistake because

On successful completion of the above, I started searching the solutions on the net for a better approach. This led to posts where it was mentioned that my approach won't give correct results for large numbers as the factorial will be out of range of int and long. So, we need to use BigInteger to solve the problem.Taking the advice, I started working on updating my program to make use of BigInteger. This again was a challenge for me as I was not familiar with the availability and usage of BigInteger methods and fields. This is the final version of the program and its output.
As I was struggling with writing the above program, I googled a bit more, and this was the interesting bit I received."Recursive solution is a bad example
Writing a recursive factorial function is a mistake because
- The recursive solution's memory usage is O(N) instead of O(1).
- It's more complicated for students.
- It's inappropriate when the iterative solution is better.
Closing for the day, will be back with another program tomorrow.
Comments