I am trying to reduce a number to a desired range of values, say x until it is less than 100. What I am doing is dividing the number by 10 until it is less than 100.
What would be a better approach, recursion or iteration?
Recursive approach is usually more expensive in terms of execution time (because method calls introduce additional overhead). Additionally, it may result in StackOverflow exception if recursion is too deep (may not be applicable to your case, though, if your initial number is small enough to keep the number of recursive calls low)
Therefore, iteration is preferred.
I would prefer an iterative approach over a recursive approach. A cool thing you can do is.
for (;num > 100; num /=10) {}
Where num
is the number you are dividing.
At the end of the day, the compiler will find the best thing to do generally, so design your programs in a way that you find most logical.
Recursion is less efficient than iteration as there is usually more overhead associated with making recursive calls due to the fact that the call stack is so heavily used during recursion.
Also iteration is easy to understand and maintain than recursive calls. In some cases based on how you write the algorithm the code complexity might be higher for recursive algorithm. see Iterative and recursive version has same complexity?
Iteration is your friend here.
Iteration: "repeat something until it's done."
Recursion: "Solve a large problem by breaking it up into smaller and smaller pieces until you can solve it; combine the results."
Recursion is also much slower usually, and when iteration is applicable it's almost always prefered.
Related question: Recursion vs Iteration.
What is recursion and when should I use it?