Skip to content

Instantly share code, notes, and snippets.

@idealhack
Created May 13, 2013 10:15
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/5567361 to your computer and use it in GitHub Desktop.
Save idealhack/5567361 to your computer and use it in GitHub Desktop.
Use recursion to achieve factorial calculation (20090120)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Factorial
{
class Program
{
public long Factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return n * Factorial(n - 1);
}
}
static void Main(string[] args)
{
Program p = new Program();
long sum = 0;
for (int i = 1; i < 11; i++)
{
sum += p.Factorial(i);
}
Console.WriteLine("1! + 2! + ... + 10! = " + sum);
}
}
}

According to the characteristics of factorial calculation, using recursion to achieve it is very convenient.

Note that recursion is a kind of low efficiency algorithm, especially when calculate with larger operations, so give careful consideration to the circumstances in deciding whether to use it.

This is a example of algorithm I wrote when learning C# programming language.

Example: Calculate 1! + 2! + … + 10! and print out the results. Use recursion to achieve it.

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