冰雹序列C ++递归

时间:2019-02-14 06:13:56

标签: c++ loops recursion

将以下代码从使用循环转换为仅使用递归时遇到了麻烦。

//longestHailstoneStartValue also cycles through each of the sequences from 1 
//to 'n' and after it is determined what the largest length is, it finds which 
//number corresponds with the longest length function.
//
//Sample input: '8'
//Sample output: '7'
//'7' is from the sequence starting with 7.

int longestHailstoneStartValue(int n)
{
    int u=1, w=0, z=0;

while(n>=u)
{
    if(w<lengthHailstone(u))
    {
        w=lengthHailstone(u);
        z=u;
    }

    u++;
}

return z;
}

我必须将其转换为递归,并且无论如何都应使用未使用的任何额外变量/其中已存储新值。

1 个答案:

答案 0 :(得分:1)

您必须取出变量z,因为它实际上是无用的,无非就是存储u的值,这会增加将u的值复制到的内存。 z ...

另外,请阅读有关recursion to know more about what it actually is的信息...它只是从其自己的定义中一次又一次地调用相同的方法...

int longestHailstoneStartValue(int n)
{
    int u = 1, w = 0;
    if(w < lengthHailstone(u))
        w = lengthHailstone(u); // Removed 'z'...
    u++;
    /* '?' is the ternary operator... If n is greater or equal to u then print the
       original value of u (Note the 'u++') or else recursively call the function till
       the condition 'n >= u' is satisfied... */
    return n >= u ? u - 1 : longestHailstoneStartValue(n); /* 'u - 1' since 'u' will
                                                               increment by 1 even when
                                                               the given condition is
                                                               true... */
}