-
-
Save oyms/e7bad5882dd8495246b5a9045c474444 to your computer and use it in GitHub Desktop.
PrimeFinder recursive
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.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