【问题标题】:How to multiply and print the digits of 2 numbers recursively如何递归地乘以和打印2个数字的数字
【发布时间】:2019-01-17 08:52:56
【问题描述】:

我正在寻找一种方法来递归地乘以两个数字的数字(不一定具有相同的数字长度),而无需以下列方式使用循环: 假设数字是 123 和 567。我正在想办法打印:

5
6
7
10
12
14
15
18
21

它是第一个数字的最左边的数字乘以第二个数字的每个数字,从左边开始并在最右边移动。

函数必须适合原型:

void multi(int a, int b);

我已经设法从那里递归地跳到 1 和 5 到 1 56 和 1 567,并且在每次调用中我都会打印 a%10 * b%10 的结果。 但是当回溯到 12 567 时,函数又会跳到 1 567。

这是我最好的尝试:

    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);
}

限制列表:

no loops
single function
mandatory prototype

【问题讨论】:

  • 请同时发布您尝试的代码。
  • 哪种语言 cc++
  • @c360 您使用 C 或 C++ 编写代码。您使用的是 C 编译器还是 C++ 编译器?相应地调整问题标签。并发布您迄今为止的尝试。
  • @c360 在 SO 上,习惯上每个问题询问一种语言。
  • @pmg 这不符合函数原型?

标签: c recursion


【解决方案1】:

这是一个可能的解决方案:

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));
}

可测试HERE

【讨论】:

  • 太棒了!简单,清晰且符合限制。非常感谢!
  • @c360 好吧,不客气,但它本可以进一步简化......
【解决方案2】:

这里的问题是,您需要为每个 sub a 值和所有 sub b 值运行一个例程。

我认为您在这里需要更多的分歧同意方法。您发送了减少的值,但您没有正确处理所有情况。

我会建议一种更简单的方法,它采用值 a 和 b,然后为每个 a 子值运行一个例程,通过每次传递整个 b 来显示所有不同的情况。 这样对于每个 sub a 值,您都会得到与 sub b 值的所有乘法。

 #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;
}

希望这是清晰和有用的,祝你好运

【讨论】:

  • 谢谢,这很清楚,唯一的问题是我需要一个解决方案,它使用一个功能与我提到的原型。 (限制不使用任何循环)我保证存在这样的解决方案,但我无法弄清楚。我尝试了一些技巧,例如递归调用和在 a 和 b 之间切换位置。我也尝试将打印顺序更改为递归之前或之后。
  • 将限制添加到问题中。在一个地方列出一个简明的列表:没有循环、单一功能、强制原型……这样可以更容易地发现像这样的答案,这些答案不适合,因此不是问题的真正答案。
猜你喜欢
  • 2020-08-22
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2023-04-05
  • 2022-01-18
  • 2023-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多