I was bored and burnt out on more serious projects.... until I saw this Computerphile video on YouTube. Now I'm inspired again. Now I feel like spending some time implementing that recursive algorithm in a little console program. Fortunately, recursion is unbearably slow in this case. So, I ended up writing a small class that implements a loop algorithm to find any \$F_n\$.
I'm just learning C#, so I'm most concerned with best practices and style. I want to get a good foundation though, so all feedback is welcome.
Particular Concerns
- Is my indentation correct?
- Have I named my variables horribly? (I think they smell a bit.)
- Which implementation is better? I'm feeling like it's six of one or a half doz. of the other.
- Should I be concerned about hitting the upper boundary of the
ulong
type? Fibonacci numbers grow very quickly. Is there a better representation of very large numbers?
Fibonacci
class Fibonacci
{
private int _n;
private ulong _value;
private ulong _FnMinus1;
private ulong _FnMinus2;
public int n
{
get { return _n; }
set { _n = value; }
}
public ulong Value
{
get {return _value;}
//set { _value = value; }
}
public void Calculate()
{
if (n <= 0)
{
throw new ArgumentOutOfRangeException("n","Can't calculate Fn when n is less than or equal to zero.");
}
else if (n == 1 || n == 2)
{
_value = 1;
}
else
{
//initialize previous results
_FnMinus1 = 1;
_FnMinus2 = 1;
for (int i = 0; i <= (n - 2) ; i++)
{
_value = _FnMinus1 + _FnMinus2;
_FnMinus2 = _FnMinus1;
_FnMinus1 = _value;
}
}
}
//constructors
public Fibonacci(int n)
{
_n = n;
Calculate();
}
public Fibonacci() { }
}
Implementation1
class Program
{
static void Main(string[] args)
{
Fibonacci fib = new Fibonacci();
for (int i = 1; i <= 50; i++)
{
fib.n = i;
fib.Calculate();
Console.WriteLine(fib.Value);
}
Console.WriteLine("Press enter to close...");
Console.ReadLine();
}
}
Implementation2
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 50; i++)
{
Fibonacci fib = new Fibonacci(i);
Console.WriteLine(fib.Value);
}
Console.WriteLine("Press enter to close...");
Console.ReadLine();
}
}
Update: Follow up question here.
BigInteger
class. \$\endgroup\$ulong
that is) overflow:System.OverflowException: Arithmetic operation resulted in an overflow.
Just change the limit in the for loop in the implementation 1 and you will get an exception; unless it's run in an unchecked environment, in which case it overruns happily and silently and just gives out a wrong answer. \$\endgroup\$