Skip to content

Instantly share code, notes, and snippets.

@idg10
Created October 6, 2022 08:48
Show Gist options
  • Save idg10/691da8caab38f5626f29e5db65b9c7dd to your computer and use it in GitHub Desktop.
Save idg10/691da8caab38f5626f29e5db65b9c7dd to your computer and use it in GitHub Desktop.
Idiomatic C# Fibonnaci
// Written as a reply to https://twitter.com/buhakmeh/status/1577738711013335040
// (C) 2022 I D Griffiths
IEnumerable<BigInteger> FibonnaciEndless()
{
BigInteger i = 0, n = 1;
while (true)
{
yield return i;
(i, n) = (n, i + n);
}
}
// 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> FibonnaciList(int num) => Fibonnaci(num).ToList();
foreach (BigInteger i in FibonnaciList(10))
{
Console.WriteLine(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment