冰雹序列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... */
}
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败