Back to track
#23 Easy Foundations

Recursion Factorial

Open the editor

Problem

Compute factorial using recursion.

Constraints

0 <= n <= 20

Hints

  1. 1

    Base case n==0

  2. 2

    Return n*fact(n-1)

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

long long fact(int n) {
  if (n <= 1) return 1;
  return n * fact(n - 1);
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  cout << fact(n) << '\n';
  return 0;
}

© 2026 ChitChat