Skip to content

Instantly share code, notes, and snippets.

@jvitkauskas
Created November 7, 2018 22:49
Show Gist options
  • Save jvitkauskas/716cb9a7217e3de241fe34a4be48b8a8 to your computer and use it in GitHub Desktop.
Save jvitkauskas/716cb9a7217e3de241fe34a4be48b8a8 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
// implementation of "To Infinity & Beyond - Computerphile" in C# (https://www.youtube.com/watch?v=bnRNiE_OVWA)
namespace ConsoleApp1
{
static class Program
{
static void Main(string[] args)
{
// not really infinite, because int has a maximum value
// if "true" infinity is needed, a custom type should be used
var infinite = Enumerable.Range(1, int.MaxValue);
// step 1: take 20 elements
Print(infinite.Take(20));
// step 2: print the factors of 15
Print(Factors(15));
// step 3: prints if 15 is prime
Console.WriteLine(Prime(15));
// step 4: print all primes (1st method)
Print(infinite.Where(Prime));
// step 5: print all primes (2nd method)
Print(Primes());
// step 6: twins
Print(Primes().Zip(Primes().Skip(1), (a, b) => (a, b)).Where(Twin));
}
static IEnumerable<int> Factors(int n) => Enumerable.Range(1, n).Where(x => n % x == 0);
static bool Prime(int n) => Factors(n).SequenceEqual(new [] { 1, n });
static IEnumerable<int> Primes() => Sieve(Enumerable.Range(2, int.MaxValue-1));
static IEnumerable<int> Sieve(IEnumerable<int> enumerable)
{
var (p, ps) = enumerable.ToHeadTails();
yield return p;
foreach (var value in Sieve(ps.Where(x => x % p != 0)))
{
yield return value;
}
}
private static bool Twin((int x, int y) tuple) => tuple.y == tuple.x+2;
// helper methods below
static (T x, IEnumerable<T> xs) ToHeadTails<T>(this IEnumerable<T> enumerable)
{
var enumerator = enumerable.GetEnumerator();
enumerator.MoveNext();
return (enumerator.Current, enumerator.ToEnumerable());
}
static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
static void Print<T>(IEnumerable<T> enumerable)
{
foreach (var value in enumerable)
{
Console.Write(value + ",");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment