Skip to content

Instantly share code, notes, and snippets.

@idg10
Last active October 6, 2022 08:49
Show Gist options
  • Save idg10/8c84285c610da8525375e4dbd17bf965 to your computer and use it in GitHub Desktop.
Save idg10/8c84285c610da8525375e4dbd17bf965 to your computer and use it in GitHub Desktop.
LINQy C# Fibonnaci
// Written as a reply to https://twitter.com/buhakmeh/status/1577738711013335040
// (C) 2022 I D Griffiths
// EnumerableEx from System.Interactive
IEnumerable<BigInteger> FibonnaciEndless() => EnumerableEx.Generate(
(i: new BigInteger(0), n: new BigInteger(1)),
_ => true,
s => (s.n, s.i + s.n),
s => s.i);
// Why num + 1? Because Khalid's example also returns 11 numbers when you ask it
// for 10.
IEnumerable<BigInteger> Fibonnaci(int num) => FibonnaciEndless().Take(num + 1);
// ...and if you really want a list
IEnumerable<BigInteger> FibonnaciLinqy(int num) => Fibonnaci(num).ToList();
foreach (BigInteger i in FibonnaciLinqy(10))
{
Console.WriteLine(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment