C# Implementation of Problem 14
View source code here on GitHub!
1/*
2Project Euler Problem 14
3
4This was easier to do in C# than I would have thought
5
6Problem:
7
8The following iterative sequence is defined for the set of positive integers:
9
10n → n/2 (n is even)
11n → 3n + 1 (n is odd)
12
13Using the rule above and starting with 13, we generate the following sequence:
1413 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
15
16It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been
17proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
18
19Which starting number, under one million, produces the longest chain?
20
21NOTE: Once the chain starts the terms are allowed to go above one million.
22*/
23using System;
24
25namespace Euler
26{
27 public class p0014 : IEuler
28 {
29 public object Answer()
30 {
31 int biggestSeen = 0;
32 ulong biggestIdx = 0;
33 Dictionary<ulong, int> cache = new();
34 for (ulong x = 1; x < 1000000; x += 1)
35 {
36 int result = CollatzLen(x, cache);
37 if (result > biggestSeen)
38 {
39 biggestSeen = result;
40 biggestIdx = x;
41 }
42 }
43 return (int)biggestIdx;
44 }
45
46 static int CollatzLen(ulong n, IDictionary<ulong, int> cache)
47 {
48 if (n == 1)
49 return 0;
50 else if (cache.ContainsKey(n))
51 return cache[n];
52
53 int result;
54 if (n % 2 == 0)
55 result = 1 + CollatzLen(n / 2, cache);
56 else
57 result = 2 + CollatzLen((3 * n + 1) / 2, cache);
58 cache.Add(n, result);
59 return result;
60 }
61 }
62}