这是这个问题的背景:
背景 取大于 1 的任意整数 n 并应用以下算法
如果 n 是奇数则 n = n × 3 + 1 否则 n = n/2
如果n等于1则停止,否则转第1步
下面演示了当使用 6 的起始 n 时会发生什么
6 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1
经过 8 代算法后,我们得到 1。 据推测,对于每个大于 1 的数字,重复应用该算法将 最终达到 1。
问题是我怎样才能找到一个数字,正好需要 500 代才能减少到 1?
下面的代码是我的版本,但似乎有一些错误的逻辑。你能帮我改正这个吗?提前致谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sequence1
{
class Program
{
static void Main(string[] args)
{
int start = 1;
int flag = 0;
int value;
while(true){
int temp = (start - 1) / 3;
string sta = temp.ToString();
if (Int32.TryParse(sta, out value) )
{
if (((start - 1) / 3) % 2 == 1)
{
start = (start - 1) / 3;
flag++;
if (flag == 500)
{
break;
}
}
else
{
start = start * 2;
flag++;
if (flag == 500)
{
break;
}
}
}
else
{
start = start * 2;
flag++;
if (flag == 500)
{
break;
}
}
}
Console.WriteLine("result is {0}", start);
Console.ReadLine();
}
}
}
最佳答案
由于你的问题的标题是“一个递归相关的问题”,我会给你一个递归的解决方案。
int Process(int input, int maxRecursionDepth)
{
// condition to break recursion
if (maxRecursionDepth == 0 || input == 1)
return input;
if (input % 2 == 1) // odd case
return Process(input * 3 + 1, maxRecursionDepth - 1);
else // even case
return Process(input / 2, maxRecursionDepth - 1);
}
现在要查找指定范围内的所有数字,在恰好 500 次递归后返回 1:
int startRange = 1, endRange = 1000;
int maxDepth = 500;
List<int> resultList = new List<int>();
for (int i = startRange; i <= endRange; i++)
{
if (Process(i, maxDepth) == 1)
resultList.Add(i);
}
关于c# - c#中的递归相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229991/