Easy–medium · accumulation

Factorial

Read N and print N! = 1 × 2 × … × N. Same accumulator skeleton as Sum from 1 to N — but multiplied, and with a hard ceiling you'll discover the interesting way.

At a glanceMultiply 1 through N into a long long — 12! = 479,001,600 is the last factorial that fits in a 32-bit int, and 0! is 1, not 0.

Problem

Input: one integer N (0 ≤ N ≤ 12).

Output: N!.

Samples:

InputOutput
5120
01

Why the ceiling at 12? Because 12! = 479,001,600 fits in a 32-bit int — and 13! doesn't. The limit is the lesson.

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — start at 1, not 0

The accumulator starts at 1 (multiplying by 0 would erase everything — this "neutral value" is called the identity element). Then for (int i = 1; i <= n; i++) r *= i;.

Hint 2 — the N = 0 edge

By definition 0! = 1. With the loop above, N = 0 runs zero iterations and the accumulator stays 1 — the right answer falls out for free. When edge cases cost you no extra code, your structure is right.

Solution (try it first!)
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int r = 1;
    for (int i = 1; i <= n; i++) {
        r *= i;
    }
    cout << r << endl;
    return 0;
}

The overflow cliff: 12! = 479,001,600 fits in int (max ≈ 2.1 billion); 13! silently wraps to garbage — no error, just wrong numbers. Bigger factorials need long long on a real compiler (up to 20!) or big-integer techniques. Overflow is also why types and their limits matter, not just syntax.

Deep dive

Why this works

An accumulator that multiplies, and the first place where the answer stops fitting the type you picked. Growth rate becomes the subject.

The cost

O(n) multiplications. 13! = 6,227,020,800 already exceeds a signed 32-bit int.

Where it goes wrong

  • int overflows at 13! silently — you get a plausible-looking wrong number, not an error.
  • Seeding the product with 0 instead of 1 makes every answer 0.

Next step

Growth you cannot compute directly: Fibonacci.

Two things to remember

  • 13! overflows int; 21! overflows unsigned long long.
  • Products start at 1, sums start at 0.
🐞 This version fails — open it and try

Seeds the product with 0 — everything becomes 0

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    long long f = 0;
    for (int i = 1; i <= n; i++) f *= i;
    cout << f << endl;
    return 0;
}