Skip to content

Instantly share code, notes, and snippets.

@bitwalker
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitwalker/f0d717d7424ce07eb2ae to your computer and use it in GitHub Desktop.
Save bitwalker/f0d717d7424ce07eb2ae to your computer and use it in GitHub Desktop.
.NET Newsletter #1 - Challenge
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