Just sharing some of my inconsequential lunch conversations with you... RSS  

Wednesday, September 26, 2007

Fibonacci in C#

Ok, I couldn't wait for the weekend. Here's my first try:



namespace Fibonacci
{
class Program
{
public static IEnumerable fib(int number)
{
int counter = 0;
int a = 0, b = 1;

while (counter++ < number)
{
yield return b;

int previousA = a;

a = b;
b = previousA + b;
}
}

static void Main(string[] args)
{
// Display fib
foreach (int i in fib(10))
{
Console.WriteLine("{0} ", i);
}
}
}
}


3 comments:

Anonymous said...

Hi Mario.

I saw your fibonacci method and I didn't like the way we need three lines of code to switch the values between two variables. It started me thinking and I came up with a solution:

a = a + b - (b = a);

Hope you like it.

Anonymous said...

Ok, after talking to Mario we noticed that for fibonacci we don't need a swap. So, these three lines of code:

int previousA = a;
a = b;
b = previousA + b;

can be changed for one line:

b = a + (a = b);

Mário Romano said...

Cool! Never though of it! Thanks, I'll refactor my Fibonacci C# version and will posted soon.

The only doubt I have is about overflowing - I'll have to check it.

Now that we're talking about readability, I also love the boo implementation:

a, b = b, a + b

This push/pop strategy seems another great alternative, with a great focus on readability.

Tanks for this great comment.

Development Catharsis :: Copyright 2006 Mário Romano