我创建了2个列表,一个用于数字,另一个用于链计数。如果数字在数字列表中,请将其计数并将其添加到当前链计数中。我在这里的问题是程序停滞不前,并没有给我任何回报。这个问题本身已经解决了,我需要花费4.7秒才能找到一百万以下的数字,它具有最长的序列和链数,但我想用缓存来优化它。
static List<long> cache_number = new List<long>();
static List<long> cache_chains = new List<long>();
static long CollatzChain(long num) {
int chain = 1;
while (num != 1) {
if(cache_number.Contains(num)){
long x = chain + cache_chains[cache_number.IndexOf(num)];
return x;
}
if (num % 2 == 0) {
num = num / 2;
}
else {
num = 3 * num + 1;
}
chain++;
}
cache_number.Add(num);
cache_chains.Add(chain);
return chain;
}
static void Main(string[] args){
Stopwatch time = new Stopwatch();
time.Start();
List<long> chain = new List<long>();
List<long> numbers = new List<long>();
for (int i = 13; i < 1000000; i++) {
numbers.Add(i);
chain.Add(CollatzChain(i));
}
time.Stop();
long elapsed = time.ElapsedMilliseconds;
Console.WriteLine("The longest chain was made by number {0} with a chain of {1} elements", numbers[chain.IndexOf(chain.Max())], chain.Max());
Console.Write("Time Elapsed: {0} ms", elapsed);
Console.ReadKey();
}