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:


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.
This was an eye opener, and I returned back to my simple solution of using a for-loop, with BigInteger though. Here is the final program for the day:



 
 
 
 
 
 
Closing for the day, will be back with another program tomorrow.

 

Comments

Popular posts from this blog

Day#3 of Java Programming Practice- Longest word of a Sentence

Book Review: Those Pricey Thakur Girls

Day# 5 of Java Programming Practice- Change the first letter of each word in a sentence to Uppercase.