#include // Implement a program that queries the user for an // integer 'n' and then calculates and prints 'n!!', // the double factorial. The double factorial appears // in some engineering models. // // If n < 0, simply return 0 and do nothing. // If 'n' is even, then n!! = n*(n - 2)*(n - 4)*...*4*2. // If 'n' is odd, then n!! = n*(n - 2)*(n - 4)*...*5*3*1. // // For example, // 0!! = 1 // 1!! = 1 // 2!! = 2 // 3!! = 3 // 4!! = 8 // 5!! = 15 // 6!! = 48 // 7!! = 105 // 8!! = 384 // 9!! = 945 // 10!! = 3840 // 11!! = 10395 // 12!! = 46080 // // Scroll down first for a hint and then for solutions. // // Note that n!! is not equal to (n!)! // Function declarations int main(); // Function definitions int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; std::cout << n << "!! = " << 1 << std::endl; return 0; } // Hint: You could use a conditional statement // and calculate the double factorial differently // depending on whether 'n' is even or odd. // // Alternatively, observe that 0!! = 1!! = 1. // You can initialize the result to 1, start a // loop at 'n', and count down by 2 until there // are no more factors to multiply. // This is one solution: /* int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; if ( n < 0 ) { return 0; } int double_factorial{ 1 }; for ( int k{ n }; k > 1; k -= 2 ) { double_factorial *= k; } std::cout << n << "!! = " << double_factorial << std::endl; return 0; } */ // This is another solution: /* int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; if ( n < 0 ) { return 0; } int double_factorial{ 1 }; if ( n%2 == 0 ) { // 'n' is even. for ( int k{ 2 }; k <= n; k += 2 ) { double_factorial *= k; } } else { // 'n' is odd. for ( int k{ 3 }; k <= n; k += 2 ) { double_factorial *= k; } } std::cout << n << "!! = " << double_factorial << std::endl; return 0; } */