How to multiply and print the digits of 2 numbers recursively

Viewed 521

I'm looking for a way to multiply the digits of two numbers (not necessarily of the same digits length) recursively without using loops in the following way: let's say the numbers are 123 and 567. I'm trying to figure out a way to print:

5
6
7
10
12
14
15
18
21

it's the left most digit of the first number times every digit of the second number starting from the left and moving in both the right most.

the function must fit the prototype:

void multi(int a, int b);

I've managed to dive recursively to 1 and 5 from there to 1 56 and then 1 567 and in every call I print the result of a%10 * b%10. but when backtracking to 12 567 the function dives to 1 567 again.

here's my best attempt:

    int main()
{
    int a, b;
    scanf("%d %d", &a, &b);
    multi(a, b);
    return 0;
}
void multi(int a, int b)
{
    if (a == 0)
        return;
    multi(a / 10, b);
    if(b /10 != 0)
        multi(a, b / 10);
    printf("%d\n", a % 10 * b % 10);
}

list of restricions:

no loops
single function
mandatory prototype
2 Answers

Here the catch is that you need to run a routine for each sub a value of a with all of sub b values.

I think you need a bit more of divide a concur approach here. you send your reduced values but you fail to treat all the cases properly.

I would suggest a simpler approach which takes the values a and b, then for each a sub value run a routine to show all of the different cases by passing the entire b each time. so that for each sub a value you get all of the multiplications with the sub b values.

 #include <stdio.h>


 static void AuxMul(int a, int b)
 {
     int bs;
     if(0 == b)
     {
         return;
     }
     bs = b%10; /*save res for multipication */

     AuxMul(a, (b/10)); /*now sent it back with the same a value and reduced b value */
     printf("|%d| \n", (a*bs));
 }

 void MultPrintRec( int a, int b)
 {
     int as = 0;
     if (0 == a )
     {
         return;
     }
     as = a%10; /*get the value to mult. with all the b values */
     MultPrintRec(a/10, b); /*do this until there is nothing to send */
     AuxMul(as, b); /*send to a rec aux function that will take care of sub a value sent with all of the sub b values*/

 }


int main() {

    MultPrintRec(123, 567);
    return 0;
}

Hope this is clear and helpful, Good luck

This is a possible solution:

void multi(int a, int b)
{
    // First "consume" the first parameter
    if ( a > 9)
        multi(a / 10, b);

    // Then the second, passing only one digit of the first
    if ( b > 9 )
        multi(a % 10, b / 10);

    // Multiply the last digits before backtracking
    printf("%d\n", (a % 10) * (b % 10));
}

Testable HERE.

Related