[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppFactorial

(C++) Calculating the factorial

There are three ways:

plain function

A for-loop withing the function.

  1. include <cassert>
int Factorial(const int n) { assert(n>=0); int result = 1; for (int i=1; i<=n; ++i) { result*=i; } return result; } int main() { assert(Factorial(0)==1); assert(Factorial(1)==1); assert(Factorial(2)==2); assert(Factorial(3)==6); assert(Factorial(4)==24); assert(Factorial(5)==120); }


recursive function

With run-time checking using assert.

  1. include <cassert>
//The common recursive function int Factorial(const int n) { assert(n >= 0); if (n==0) return 1; return (n * Factorial(n-1)); } int main() { assert(Factorial(0)==1); assert(Factorial(1)==1); assert(Factorial(2)==2); assert(Factorial(3)==6); assert(Factorial(4)==24); assert(Factorial(5)==120); }


template metaprogram

With compile-time checking using the template version of assert.

//The compile-time assert
template <bool>
struct CtAssert;
template <>
struct CtAssert<true> {};
//The template metaprogram for factorial
template <unsigned int N>
struct factorial
{
  static unsigned const value = N * factorial<N-1>::value;
};
template <>
struct factorial<0>
{
  static unsigned const value = 1;
};
int main()
{
  CtAssert<(factorial<0>::value==1)>();
  CtAssert<(factorial<1>::value==1)>();
  CtAssert<(factorial<2>::value==2)>();
  CtAssert<(factorial<3>::value==6)>();
  CtAssert<(factorial<4>::value==24)>();
  CtAssert<(factorial<5>::value==120)>();
}


Code links



last edited (May 18, 2007) by bilderbikkel, Number of views: 2454, Current Rev: 5 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.