constexpr

Lab C++ Intermediate 20 points

Write a constexpr function factorial and a constexpr array of the first 10 factorials computed at compile time. Read indexes and print the stored values.

Input

n, then n indexes 0–9.

Output

n lines.

Example

Input

3
0
5
9

Output

1
120
362880
Sample input available Sample output available
Editor
C++

Hints

constexpr functions can run at compile time.

static_assert checks a condition while compiling.

Solution explanation

Work done at compile time costs nothing when the program runs.

Show solution
#include <iostream>
#include <array>
using namespace std;

constexpr long long factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}

constexpr array<long long, 10> makeTable() {
    array<long long, 10> t{};
    for (int i = 0; i < 10; i++) t[i] = factorial(i);
    return t;
}

constexpr auto TABLE = makeTable();
static_assert(TABLE[5] == 120, "5! must be 120");

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        int k;
        cin >> k;
        cout << TABLE[k] << "\n";
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD