递归问题缺少乘法

5uzkadbs  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(208)

**已关闭。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想要改进此问题?**更新问题,使其位于堆栈溢出主题上。

四天前关门。
改进这个问题
我有这个递归代码

public static int m(int n1, int n2) {
        int result;   
   if (n2 - n1 == 0) {          
result = n1;      }
 else {
            int mid = (n1 + n2) / 2;
            result = m(n1, mid) * m(mid + 1, n2);
        }
        return result;
    }

但是我不明白为什么递归乘法的第二部分没有执行,如果我输入一个参数(2,3),结果是6,但在我下面的计算中是120

m(2,3)
              mid= 5+2=3
         m(2,3)   *    m(4,5)    
     mid= 2+3/2=2     mid= 4+5/2=4
   m(2,2) * m(3,3)    m(4,4)  * m(5,5)

      2     *   3         4   *   5
                  6 * 20
                     120

你能解释一下为什么吗谢谢

ykejflvf

ykejflvf1#

这在一开始可能会让人感到困惑(当然,您可以根据需要进行修改),但有时它有助于:
在修改变量时打印它们。
分解同一行上的递归调用以打印中间结果。

public static int m(int n1, int n2) {
    System.out.printf("%nMethod entered: n1 = %d  n2 = %d%n", n1, n2);
    int result;
    int firstCall;
    int secondCall;
    if (n2 - n1 == 0) {
        result = n1;
    } else {
        int mid = (n1 + n2) / 2;
        System.out.printf("mid = %d%n", mid);
        System.out.printf("firstCall =  m(n1 = %d, mid %d)%n", n1,mid);
        firstCall = m(n1, mid);
        System.out.printf("secondCall = m(mid+1 = %d, n2 = %d)%n",mid+1,n2);
        secondCall = m(mid+1,n2);
        System.out.printf("result = firstCall{%d} * secondCall{%d}%n", firstCall, secondCall);
        result = firstCall * secondCall;
        System.out.printf("result = %d%n", result);
    }
    return result;
}

当使用m(2,5)运行时,它会打印

Method entered: n1 = 2  n2 = 3
mid = 2
firstCall =  m(n1 = 2, mid 2)

Method entered: n1 = 2  n2 = 2
secondCall = m(mid+1 = 3, n2 = 3)

Method entered: n1 = 3  n2 = 3
result = firstCall{2} * secondCall{3}
result = 6
secondCall = m(mid+1 = 4, n2 = 5)

Method entered: n1 = 4  n2 = 5
mid = 4
firstCall =  m(n1 = 4, mid 4)

Method entered: n1 = 4  n2 = 4
secondCall = m(mid+1 = 5, n2 = 5)

Method entered: n1 = 5  n2 = 5
result = firstCall{4} * secondCall{5}
result = 20
result = firstCall{6} * secondCall{20}
result = 120
120
de90aj5v

de90aj5v2#

我认为你在第一步计算中间值是错误的。正确的递归树应该是-

m(2,3)
          mid = 2 [=5/2] 
     m(2,2)   *    m(3,3)    
        2     *       3         
              = 6

相关问题