Created
October 19, 2020 14:35
-
-
Save yuchiki/0717ffb2266ae161074bfcff272768dc to your computer and use it in GitHub Desktop.
length of Collatz series from n to 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace collatz { | |
class Program { | |
static void Main(string[] args) { | |
IEnumerable<T> iterate<T>(T seed, Func<T, T> step) { | |
while (true) { | |
yield return seed; | |
seed = step(seed); | |
} | |
} | |
Func<int, int> nextCollatz = n => | |
n % 2 == 0 ? n / 2 : n * 3 + 1; | |
Console.WriteLine("(はじまり, 1になるまでの長さ)"); | |
Console.WriteLine(string.Join( | |
"\n", | |
Enumerable.Range(2, 100) | |
.Select(n => iterate(n, nextCollatz)) | |
.Select(list => list.TakeWhile(x => x != 1)) | |
.Select(list => (list, list.Count())) | |
.OrderByDescending(x => x.Item2) | |
.Take(20) | |
.Select(x => $"({x.Item1.First()}, {x.Item2})"))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment