Last active
December 17, 2015 02:08
-
-
Save DForshner/5533088 to your computer and use it in GitHub Desktop.
C# IEnumerable fibonacci sequence
This file contains hidden or 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.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