递归阶乘中的乘法顺序:n*fact() 与 fact()*n

Order of multiplications in recursive factorial: n*fact() vs. fact()*n

在递归阶乘函数中进行乘法的顺序是否有所不同,这取决于最后一个 return 是否采用 fact(n-1) * n 形式与 n * 形式事实(n-1)?

int fact(int n)
{
    if (n<2)
        return 1;
    else
        return fact(n-1)*n;
}

根据乘法交换律,fact(n-1)*nn*fact(n-1)没有区别。

关于乘法运算的顺序,fact(n-1)*n被计算为

(((1*2)*3)*4...)*n

n*fact(n-1)被评估为

n*((n-1)*((n-2)*....3*(2*1)))

Is there a difference in the order that the multiplications are done in a recursive factorial function depending on whether the last return is in the form fact(n-1) * n compared to the form n * fact(n-1) ?

不会有区别

The Commutative Laws say we can swap numbers over and still get the same answer ...

...当我们添加:

a + b = b + a

... 或者当我们相乘时:

a × b = b × a

现在接受订单是的,肯定会改变

对于 return fact(n-1)*n;

fact(4) will return fact(3)*4;
fact(3) will return fact(2)*3;
fact(2) will return fact(1)*2;
fact(1) will return 1;

所以下单

1*2;
2*3;
6*4;

return n*fact(n-1);

fact(4) will return 4*fact(3);
fact(3) will return 3*fact(2);
fact(2) will return 2*fact(1);
fact(1) will return 1;

所以下单

2*1;
3*2;
4*6