• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // TestFactorial.cpp
2 //
3 // Factorials and Binomial Coefficients.
4 //
5 // Copyright Datasim Education BV 2009-2010
6 // Copyright John Maddock and Paul A. Bristow 2010
7 
8 // Use, modification and distribution are subject to the
9 // Boost Software License, Version 1.0.
10 // (See accompanying file LICENSE_1_0.txt
11 // or copy at http://www.boost.org/LICENSE_1_0.txt)
12 
13 #include <boost/math/special_functions/factorials.hpp>
14 #include <boost/math/special_functions.hpp>
15 
16 #include <iostream>
17 using namespace std;
18 
main()19 int main()
20 {
21   using namespace boost::math;
22 
23   // Factorials
24   unsigned int n = 3;
25 
26   try
27   {
28      cout << "Factorial: " << factorial<double>(n) << endl;
29 
30      // Caution: You must provide a return type template value, so this will not compile
31      // unsigned int nfac = factorial(n); // could not deduce template argument for 'T'
32      // You must provide an explicit floating-point (not integer) return type.
33      // If you do provide an integer type, like this:
34      // unsigned int uintfac = factorial<unsigned int>(n);
35      // you will also get a compile error, for MSVC C2338.
36      // If you really want an integer type, you can convert from double:
37      unsigned int intfac = static_cast<unsigned int>(factorial<double>(n));
38      // this will be exact, until the result of the factorial overflows the integer type.
39 
40      cout << "Unchecked factorial: " << boost::math::unchecked_factorial<float>(n) << endl;
41      // Note:
42      // unsigned int unfac = boost::math::unchecked_factorial<unsigned int>(n);
43      // also fails to compile for the same reasons.
44   }
45   catch(exception& e)
46   {
47     cout << e.what() << endl;
48   }
49 
50   // Double factorial n!!
51   try
52   {
53     //cout << "Double factorial: " << boost::math::double_factorial<unsigned>(n);
54   }
55   catch(exception& e)
56   {
57     cout << e.what() << endl;
58   }
59 
60   // Rising and falling factorials
61   try
62   {
63     int i = 2; double x = 8;
64     cout << "Rising factorial: " << rising_factorial(x,i) << endl;
65     cout << "Falling factorial: " << falling_factorial(x,i) << endl;
66   }
67   catch(exception& e)
68   {
69     cout << e.what() << endl;
70   }
71 
72   // Binomial coefficients
73   try
74   {
75     unsigned n = 10; unsigned k = 2;
76     // cout << "Binomial coefficient: " << boost::math::binomial_coefficient<unsigned>(n,k) << endl;
77   }
78   catch(exception& e)
79   {
80     cout << e.what() << endl;
81   }
82   return 0;
83 }
84 
85 /*
86 
87 Output:
88 
89   factorial_example.vcxproj -> J:\Cpp\MathToolkit\test\Math_test\Release\factorial_example.exe
90   Factorial: 6
91   Unchecked factorial: 6
92   Rising factorial: 72
93   Falling factorial: 56
94 
95 */
96 
97 
98