基本上,我想编写一个算法来找出哪个数字需要500次迭代才能达到1.我尝试了一些变化,但是无法做到正确。
到目前为止,这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sequence4
{
class Program
{
static void Main(string[] args)
{
long startingNumber = 1;
long count = 0;
while (count != 500)
{
startingNumber = startingNumber * 2;
count++;
startingNumber = startingNumber / 3 - 1;
count++;
}
Console.WriteLine(count);
Console.WriteLine(startingNumber);
}
}
}
编辑:更新版本的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sequence4
{
class Program
{
static void Main(string[] args)
{
int number = 2;
int count = 0;
while (count != 500)
{
if (number % 2 == 0)
{
number = 2 * number;
count++;
}
if (number % 2 != 0)
{
number = (number / 3) - 1;
count++;
}
}
Console.WriteLine(number);
Console.WriteLine(count);
}
}
}
答案 0 :(得分:2)
考虑一下,我们有一个数字 7 ,我们需要使用 Collatz猜想
来达到 1对于奇数: x = 3n + 1
对于偶数: x = n / 2
我们已经将算法 16 应用于 7 ,我们得到 1 。所以, 16 是周期长度。
现在,如果我们以上面的例子为例,我们需要从底线反向向上移动500次。 对于反向迭代,我们使用:
对于奇数: x =(n - 1)/ 3
对于偶数: x = n * 2
现在,以编程方式实现:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double output = 1;
const int iterations = 500;
for (var i = 1; i <= iterations; i++)
{
output = GetOutput(output);
Console.WriteLine("Number after {0} iterations is: {1}", i, output);
}
Console.WriteLine("Required Number is: {0}", output);
VerifyResult(output, iterations);
Console.ReadKey();
}
private static double GetOutput(double input)
{
if (input == 1)
{
return 2;
}
var output = (input - 1) / 3;
return output % 1 == 0 && output % 2 != 0 && output > 3 ? output : input * 2;
}
//To verify the above results we need this method
private static void VerifyResult(double output, int iterations)
{
//-------------------------VERIFICATION-----------------------
Console.WriteLine("Press any key to check iterations in reverse");
Console.ReadKey();
Console.WriteLine("Running validation process ...");
var n = output;
var max = n;
var count = 0;
Console.WriteLine("{0} (starting number in Collatz Sequence)", n);
while (n > 1)
{
n = n % 2 == 0 ? n / 2 : 3 * n + 1;
count++;
if (n > max) max = n;
Console.WriteLine(n);
}
if (count == iterations) //match here iterations and outputs
{
Console.WriteLine("\n\nCONGRATULATION! Verification results matched. :-)\n\n");
Console.WriteLine("There are {0} cycle length in the sequence", count);
Console.WriteLine("The largest number in the sequence is {0}", output);
Console.WriteLine("\n\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
Console.WriteLine("\n\nREQUIRED NUMBER: {0}\n\n", output);
Console.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n");
Console.WriteLine("\nPress any key to exit");
}
else
{
Console.WriteLine("Oops... Verification results are not matching. :-(");
}
}
}
}