Created
October 6, 2022 08:48
-
-
Save idg10/691da8caab38f5626f29e5db65b9c7dd to your computer and use it in GitHub Desktop.
Idiomatic C# Fibonnaci
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
// 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