c# - c#中的递归相关问题

标签 c# algorithm loops

这是这个问题的背景:

背景 取大于 1 的任意整数 n 并应用以下算法

  1. 如果 n 是奇数则 n = n × 3 + 1 否则 n = n/2

  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/

相关文章:

c# - 未找到映射

c# - 打开图像并使用相同的参数重新保存,c#

java - 如何循环 Midi 序列 Java

ios - 是否可以在后台检测用户的移动事件?

algorithm - 如何有效地对有序序列数组进行排序

sql - 如何遍历PLSQL Select的结果

python - 为什么我会收到 TypeError : '<' not supported between instances of 'int' and 'tuple' ?

c# - aspose.word 仅返回第一个表和部分

c# - 单元测试依赖于 UserManager 和 RoleManager

objective-c - 沿标尺对象的边缘绘图