【问题标题】:Hailstone Sequence C++ Recursion冰雹序列 C++ 递归
【发布时间】:2019-07-08 02:46:21
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ loops recursion


    【解决方案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... */
    }
    

    【讨论】:

    • 顺便说一句,您可能希望将lengthHailstone(u) 存储在变量中以避免重新计算值。
    • 这等价于int longestHailstoneStartValue(int n) { return n &gt;= 2 ? 1 : longestHailstoneStartValue(n); },这样就不行了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    相关资源
    最近更新 更多