【问题标题】:Multiplication table using recursion without loops使用无循环递归的乘法表
【发布时间】:2014-05-17 18:13:23
【问题描述】:

我收到了一个任务,要编写一个递归函数,该函数从用户那里接收两个整数:xy,并打印出乘法表,直到数字 x*y。 函数的原型必须完全像:void mult_table (int x, int base, int y)base 在第一次调用该函数时得到1)。 例如,如果x=4y=5,输出将是:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20

请注意,函数内部不能使用循环,但如果需要,可以使用额外的递归函数。

我的问题是: 1.如何在第 2 行和更大的行中正确地迭代基础,因为在第 1 行中,简单的 ++ 有效,但对于第二行,我已经需要 2. 我无法考虑该函数的停止情况,因为每次我要打印新行时,xy 的值都会更改。 我将非常感谢任何帮助,甚至是其他尝试方法的建议。

void mult_table (int x, int base, int y)
{
    int temp; //temp variable to hold x vlaue
    if (base <= y) //as long as base is less or equal to y, a number of line will be printed
    {
        printf(" %d", base); //using base with +1 incrementation
        mult_table(x, base+1, y);
    }
    else
    {
        printf("\n"); //start of a new line
        temp = x; //value of x is saved because it will be changed but it is still needed
        x= x+x*(1/(base-temp-1)); //new x value x+(x*1/original base of line) to reach the next x value
        y = y+y*(1/(base-temp-1)); //new y value y+(y*1/original base of line) to reach the next x value
        base = base - temp; //base is incrimented by 1 using this calcualtion
        mult_table(x, base, y); //recursdive call
    }
}

【问题讨论】:

    标签: c recursion multiplication


    【解决方案1】:

    在每次调用时将base 加一。然后您必须将base 分解为f1f2,这样f1 * f2 就是您需要在步骤base 打印的内容。我可以给你公式,但由于这是一个作业,我选择只是给你一个提示:在表格中写下 f1f2 的基值和预期值,然后你必须找到 2 个公式根据basey计算f1f2

    例如(对于 x=4 和 y=5):

    base  f1  f1
      1    1   1
      2    1   2
        ..
      4    1   5
      5    2   1
      6    2   2
        ..
    and so on
    

    提示:

    • 注意f2 是围绕一个范围循环的。想想数学上的mod(c 中的%)做了类似的事情。
    • 请注意,f1 每次k 迭代都会增长一个。认为/ 做了类似的事情。

    【讨论】:

    • @Medvednic 如果你弄明白了,请告诉我
    • np,可能是明天。
    【解决方案2】:

    编写两个递归函数,一个对x 的值进行递归,另一个对y 的值进行递归。

    #include <stdio.h>
    
    void mult_table_y(int x, int y)
    {
       if ( y != 1 )
       {
          mult_table_y(x, y-1);
       }
       printf("%d ", x*y);
    }
    
    void mult_table(int x, int y)
    {
       if ( x != 1 )
       {
          mult_table(x-1, y);
       }
       mult_table_y(x, y);
       printf("\n");
    }
    
    int main()
    {
       mult_table(5, 5);
    }
    

    【讨论】:

    • 复杂度是否等于 O(n)?
    • 由于有两个变量,我认为您无法使用O(n) 来描述它的复杂性。如果x = my = n,这需要m x n 操作。也许,您会将其复杂性描述为O(m x n)
    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2014-09-17
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多