Skip to content

Instantly share code, notes, and snippets.

@idealhack
Created May 13, 2013 10:16
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 idealhack/5567368 to your computer and use it in GitHub Desktop.
Save idealhack/5567368 to your computer and use it in GitHub Desktop.
Use recursion to achieve Fibonacci numbers (20090121)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Fibonacci
{
class Program
{
public long Fibonacci(int n)
{
if (n > 0 && (n == 1 || n == 2))
{
return 1;
}
else
{
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
static void Main(string[] args)
{
Program p = new Program();
for (int i = 1; i < 11; i++)
{
Console.Write(p.Fibonacci(i));
}
}
}
}

Fibonacci numbers refers to such an infinite numbers: 1, 1, 2, 3, 5, 8, etc. Except the first two numbers, each number is the sum of the two preceding numbers.

Since the Fibonacci numbers is defined by recurrence relation, then we can easily use recursion to achieve its calculation.

As the calculation of factorial, the bigger of the numerical calculation, the more times of recursion, and the number of redundant recursion will growth in a redundant geometric way, the efficiency of program will also be lower and lower (you can modify the program, personally test it). So you need according to the actual situation, and make a decision between readability and efficiency.

Example: Print 10 Fibonacci numbers. Use recursion to achieve it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment