DEV Community

Discussion on: Algorithms Problem Solving: Reduce to zero

Collapse
 
friesischscott profile image
FriesischScott

While this is a perfectly valid solution to the problem, this is a problem where recursion really shines and removes the need for a loop.

def reduce_number(num, counter=0):
    if num == 0:
        return counter

    if num % 2 == 0:
        return reduce_number(num / 2, counter + 1)
    else:
        return reduce_number(num - 1, counter + 1)
Collapse
 
thejoezack profile image
Joe Zack

The recursive solution is prettier, but it's not doing any less work and it ties up more memory unless your language supports tail recursion (python doesn't)

I try to avoid recursive solutions for problems like these unless the solution specifically needs back tracking.

Collapse
 
friesischscott profile image
FriesischScott

Never heard of tail recursion before. I'll look it up, thanks.