Home > Software engineering >  Write a recursive function which will accept a positive integer from user and multiplies all its dig
Write a recursive function which will accept a positive integer from user and multiplies all its dig

Time:11-19

The code that i have written below takes input and then multiplies its digits and give output. If the output is more than 1 digit, then I want to multiply its digits again and keep on repeating this process till the output is a single digit number. I want to do use recursion here.

prd = 1
def func_(num, i):
    global prd
    
    if i == len(num):
        return True
    else:
        prd = int(num[i]) * func_(num, i 1)
        return prd
num = input()
i = 0
print(func_(num, i))

Now if i run this program and enter input as 24, it gives output 8 which is correct but when i give input like 5555 then it returns 625. Now i want that this program perform same functions again with 625(that is 6*2*5) and keep on doing this till the output is a single digit number.

CodePudding user response:

If you want to run the function on your number until it is between 0-9, you can do a loop until the number is as expected. Pseudocode below

number = input
while number > 10:
    number = multiplydigits(number)
    print(number)

CodePudding user response:

I'd do something like this, if it's necessary to make it recursive.

def mult_func(num):
    #
    # multiply the digits here
    #
    if len(str(num)) != 1:
        num = mult_func(num)
    return num
res = mult_func(input("..."))
print(res)

Also note that if you are using global variable - which I don't advise - the return makes it kinda pointless. And it would be useful to provide a clear explanation with examples.

I don't really understand why are you using "i" like that. This makes the multiplication itself recursive and that's why you make only one "step".

  • Related