Skip to content

Instantly share code, notes, and snippets.

@DForshner
Last active December 17, 2015 02:08
Show Gist options
  • Save DForshner/5533088 to your computer and use it in GitHub Desktop.
Save DForshner/5533088 to your computer and use it in GitHub Desktop.
C# IEnumerable fibonacci sequence
using System;
using System.Collections;
public class NaiveFibonacciSequenceGenerator : IEnumerable
{
private readonly int sequenceSize;
public NaiveFibonacciSequenceGenerator(int sequenceSize)
{
this.sequenceSize = sequenceSize;
}
public IEnumerator GetEnumerator()
{
int n1 = 0;
int n2 = 1;
int count = 0;
while (count <= sequenceSize)
{
var n1Temp = n1;
n1 = n2;
n2 = n1Temp + n2;
++count;
yield return n2 - n1;
}
}
}
public class Program
{
static void Main()
{
// Create a generator that will generate 10 Fibonacci numbers
var generator = new NaiveFibonacciSequenceGenerator(10);
foreach (var num in generator)
{
Console.WriteLine(num);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment