Skip to content

Instantly share code, notes, and snippets.

@oyms oyms/PrimeFinder.cs Secret

Last active Dec 8, 2019
Embed
What would you like to do?
PrimeFinder recursive
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class PrimeFinder
{
public int Nth(int n) => Siphon(new Generator()).Skip(n - 1).First();
private IEnumerable<int> Siphon(SingletonIterable numbers)
{
var (head, tail) = numbers;
yield return head;
foreach (var n in Siphon(tail).Where(x => x % head != 0))
{
yield return n;
}
}
}
class Generator : SingletonIterable
{
public Generator() : base(Numbers().GetEnumerator()){}
private static IEnumerable<int> Numbers()
{
var n = 2;
while (true)
{
yield return n++;
}
}
}
class SingletonIterable : IEnumerable<int>
{
private readonly IEnumerator<int> _enumerator;
protected SingletonIterable(IEnumerator<int> enumerator)
{
_enumerator = enumerator;
}
public IEnumerator<int> GetEnumerator() => _enumerator;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void Deconstruct(out int head, out SingletonIterable tail)
{
_enumerator.MoveNext();
head = _enumerator.Current;
tail = this;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.