Home > OS >  Digit product of a number
Digit product of a number

Time:02-28

I want to practice writing a function (recursive and iterative) to give a product of a given number by multiplying its non-zero digits.

for example: 22 = 2x2 which gives you 4 and 303 = 3x3 which gives you 9

most of the solutions I found here won't really work if there is a zero in the number.

I tried the following using iterative, but still do not understand how I can code it using a recursive method.

def digitProductI(n):
    product = 1
    while n > 0:
        remainder = n
        if remainder != 0:
            product *= remainder
        n = n//10

    return product

CodePudding user response:

If you want to make your function a recursive function, you'll need a few things:

  1. The function calling itself
  2. A base case

For your function, instead of using a while loop, you can call the function itself with the new product and return that value. Then, to prevent a RecursionError, you should add a base case, which in this case is returning n if n <= 0. Writing this inn code would look something like this:

def digitProductI(n):

    # This is the base case. If n is 0, it would return 1.
    if not n:
        return 1

    # If n is non-zero, we find the remainder and call the function again with the floor divided value.
    remainder = n % 10
    if remainder:
        product = remainder
    else:
        product = 1
    return product * digitProductI(n // 10)

This would yield the same results as your original function. Just like in your function, a zero input would yield 1 as the result, and captive zeroes and trailing zeroes would be ignored.

  • Related