Skip to content
TheChatArchiveThe Chat Archive
Human-written demonstration (OpenAssistant volunteers)· OpenAssistant (human-written)Hugging Face OpenAssistant Conversations (oasst2)

Write me a program in C++ to compute the factorial of a number at compile time, using…

In OpenAssistant data, “assistant” turns were written by human volunteers as demonstrations. They are not model outputs.
  1. User

    Write me a program in C++ to compute the factorial of a number at compile time, using only C++03

  2. Assistant

    Here is a program written in C++ to compute the factorial of a number using the preprocessor:

    #include <iostream>
    
    static int const FACTORIALS[13] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 
                                        362880, 3628800, 39916800, 479001600 };
    #define FACT(n)  ((n) < 0 ? 1 : (n) > 12 ? INT_MAX : FACTORIALS[n])
    
    int main() {
      int n= 5;
      std::cout << "The factorial of " << n << " is " << FACT(n) << std::endl;
    }
    
    

    The output of this program would be:

    The factorial of 5 is 120
    

    If the user passes an argument bigger than 12, the program will output the maximum integer 2147483647. An alternative would be to throw an invalid_argument exception.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.