#include /*************************************************** * Problem: * * This program calculates the binomial coefficient * * n! * n choose k = -----------. * k!(n - k)! * * Unfortunately, the program does not work correctly * for some values of 'n' and 'k'. For example, * * 13 choose 1 * * should equal 13, but this program produces an * incorrect result. * * One approach to debugging is to add logging * statements that display intermediate values as * the program executes. * * C++ provides std::clog for diagnostic information. * This is useful because it distinguishes logging * from the normal output of the program: * * std::cout normal program output * std::clog diagnostic or logging output * std::cerr error messages * * For example, you could add * * std::clog << "n = " << n << std::endl; * * to see the value of 'n' at a particular point in * the execution. * * Add logging statements to this program to determine * why it produces the wrong answer for some inputs. * * Consider logging: * * 1. the arguments passed to factorial(...), * 2. the value of 'result' during each iteration, * 3. the three factorials calculated in main(). * * You do not have to fix the problem. Your goal is * to use logging to determine where the calculation * first goes wrong. ***************************************************/ // Function declarations int main(); int factorial( int n ); // Function definitions int main() { int n{}; std::cout << "Enter a non-negative integer: "; std::cin >> n; int k{}; std::cout << "Enter another non-negative integer: "; std::cin >> k; if ( (n < 0) || (k < 0) || (k > n) ) { return 0; } std::clog << "Calculating " << n << " choose " << k << std::endl; int nf{ factorial( n ) }; int kf{ factorial( k ) }; int nkf{ factorial( n - k ) }; std::clog << "n! = " << nf << std::endl; std::clog << "k! = " << kf << std::endl; std::clog << "(n - k)! = " << nkf << std::endl; std::cout << n << " choose " << k << " = " << nf/kf/nkf << std::endl; return 0; } int factorial( int n ) { std::clog << "factorial(" << n << ")" << std::endl; int result{ 1 }; for ( int k{ 1 }; k <= n; ++k ) { result *= k; std::clog << " k = " << k << ", result = " << result << std::endl; } return result; }