冰雹序列C 递归

Hailstone Sequence C++ Recursion

本文关键字:递归      更新时间:2023-10-16

我在使用循环中将以下代码转换为仅使用递归时遇到了一些麻烦。

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

我必须将其转换为递归,并采用任何未使用的额外变量/存储在它们中的新值的额外变量。

您必须取出变量 z,因为它实际上是没有用的,并且无非是存储u的值,这可以增加内存以将u的值复制到z ...

另外,请阅读有关递归的信息,以了解更多有关它的实际是...它只是从其自己的定义中一次又一次地调用相同的方法...

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... */
}