c Multiplication recursive function questions of language digits

Asked 1 years ago, Updated 1 years ago, 113 views

Take three natural numbers of three digits, find the product of those numbers, and then write a program as a recursive function that outputs the product of all but zero of each digit of the resulting value.

Help: The product of the three numbers in the input example is 1365300. Therefore, the product of the remaining digits except for the digit of 1 * 3 * 6 * 5 * 3 = 2701 (if the digit of 1 is 0, change it to 1 and multiply it.)

It's a code.

#include <stdio.h>

int cal(int mul, int num)
{
    if(!(mul/10))
        return num*mul;
    if(mul%10)
        return cal(mul/10, num*(mul%10));
    else
        return cal(mul/10, num);
}   

int main(void)
{
    int inp1, inp2, inp3;

    scanf("%d %d %d", &inp1, &inp2, &inp3);
    int mul = inp1*inp2*inp3;
    printf("%d", cal(mul, 1));

    return 0;
}

I think the recursive function is a method of calling, calling, calling, and going back to the called value to get the value. That's how I understood it.

I think if you keep calling num/10 in the second if statement, if the mul value is 135780, 13578 1357 135 131 This is reflected, and this reflected value is the factor value at the end and

Isn't it 1* followed by a factor value of 13* followed by a factor value of 135* followed by a factor value of 13578*? It really makes sense.

c recursive

2022-09-21 12:42

1 Answers

Let digit multiplication be a function that returns the product of each digit.

digit multiplication (123) = 1 x 2 x 3 = 6

It's easy to get.

However, instead of looking at the whole thing, if you divide 123 by 12 and 3,

digit multiplication (123) = digit multiplication (12) x 3

This relationship will be established.

This relationship is established even if you don't know what the digit multiplication function looks like. The recursive function is implemented with this relationship.

When implementing a recursive function, you always need a condition where a recursive call ends, where a single digit is entered, such as digit multiplication (1). In this case, the entry itself becomes a function value.

In the above problem, there is a condition that zero digits are not multiplied, so it seems a little difficult, but it's not that difficult. I just need to make one if condition.

Do you understand the explanation?


2022-09-21 12:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.