Skip to content

Instantly share code, notes, and snippets.

@yuchiki
Created October 19, 2020 14:35
Show Gist options
  • Save yuchiki/0717ffb2266ae161074bfcff272768dc to your computer and use it in GitHub Desktop.
Save yuchiki/0717ffb2266ae161074bfcff272768dc to your computer and use it in GitHub Desktop.
length of Collatz series from n to 1
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