Skip to content

Instantly share code, notes, and snippets.

@Nucleareal
Last active September 1, 2015 07:35
Show Gist options
  • Save Nucleareal/ba1d7f00a2d4758c93f5 to your computer and use it in GitHub Desktop.
Save Nucleareal/ba1d7f00a2d4758c93f5 to your computer and use it in GitHub Desktop.
int factorial(int n);
int main(void)
{
int a = factorial(4); // a = 4!
//
// 詳しくはfactorialを参照してもらえるとわかるが、factorial(4)は
// factorial(4)
// 4 * factorial(3)
// 4 * 3 * factorial(2)
// 4 * 3 * 2 * factorial(1)
// 4 * 3 * 2 * 1 * factorial(0)
// 4 * 3 * 2 * 1 * 1
// = 4!
// のように展開される
printf("%d\n", a);
return 0;
}
int factorial(int n)
{
if(n <= 0) //0!は1であり、0未満は定義されないのでここで止めて
{
return 1; //1を固定値として返す
}
else //そうでなければ1以上なので、この関数で求めるべき n! を n * (n-1)! に分解してあげる
{
return n * factorial(n - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment