Last active
August 29, 2015 14:20
-
-
Save bitwalker/f0d717d7424ce07eb2ae to your computer and use it in GitHub Desktop.
.NET Newsletter #1 - Challenge
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; | |
using System.Numerics; | |
public class Program | |
{ | |
public void Main(params string[] args) | |
{ | |
foreach (var n in Maths.Fib().Take(100)) | |
{ | |
Console.WriteLine(n); | |
} | |
} | |
} | |
public static class Maths | |
{ | |
/// <summary> | |
/// Produces an infinite stream of numbers following the Fibonacci sequence. | |
/// CAUTION: Do not try and consume the entire stream with ToList or ToArray, etc., | |
/// without first calling Take to restrict the number of elements produced, | |
/// otherwise it will never return. This kills the program. | |
/// </summary> | |
public static IEnumerable<BigInteger> Fib() | |
{ | |
var a = BigInteger.Zero; // F0 | |
var b = BigInteger.One; // F1 | |
var c = a + b; // F2 / first step | |
// The sequence always starts with F0, F1 | |
yield return a; | |
yield return b; | |
// Values are produced by shifting b -> a, c -> b, then | |
// adding a + b to get the next value in the sequence | |
while (true) | |
{ | |
yield return c; | |
a = b; b = c; c = a + b; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment