---
id: 370
lang: en
translation_of: index.md
source_sha256: cd8f532928cc0b291a1aadb166b2c581e7ff6ebdeea22d7781fc1b0fb9370885
title: "CH3101: Factorial Decomposition — Solution"
description: "Sieve the primes up to N, then count each prime's exponent in N! by summing floor(N / p^i) over its powers."
tags: ["OI","Math","Number Theory"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## Math Idea

I'm about to start learning some math stuff lately, and as a basic problem this one couldn't be better. First, what this problem asks is to factorize the factorial $N!=1*2*3*\dots *N$ into prime factors. We can first find the primes in the range $[1,N]$, and then find the exponents of the prime factors in this expression.

```cpp
memset(isPrime, true, sizeof(isPrime));
isPrime[1] = false;
for (int i = 2; i <= n; i++)
    if (isPrime[i])
    {
        primes.push_back(i);
        for (int factor = 2; factor * i <= n; factor++)
            isPrime[i * factor] = false;
    }
```

Next, we can show that in the factorial, for a prime $p$, its first power appears $\lfloor \frac {N} {p} \rfloor$ times, and then its second power appears $\lfloor \frac {N} {p^2} \rfloor$ times. Generalizing, we get:

$$
\lfloor \frac {N} {p} \rfloor + \lfloor \frac {N} {p^2} \rfloor + \lfloor \frac {N} {p^3} \rfloor + \dots + + \lfloor \frac {N} {p^{log_{p} N}} \rfloor
$$

Turning it into loop form, we get:

$$
\sum_{p^i \leq N}^{i = 1} \; \lfloor \frac {N} {p^i} \rfloor
$$

See the code for the details:

```cpp
// CH3101.cpp
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
#define uint unsigned int
using namespace std;
const int MX_N = 5e6 + 100;
bool isPrime[MX_N];
uint n, cs[MX_N];
vector<uint> primes;
int main()
{
    scanf("%u", &n);
    memset(isPrime, true, sizeof(isPrime));
    isPrime[1] = false;
    for (int i = 2; i <= n; i++)
        if (isPrime[i])
        {
            primes.push_back(i);
            for (int factor = 2; factor * i <= n; factor++)
                isPrime[i * factor] = false;
        }
    int siz = primes.size();
    for (int i = 0; i < siz; i++)
    {
        uint c = 0;
        for (int num = n; num; num /= primes[i])
            c += num / primes[i];
        printf("%u %u\n", primes[i], c);
    }
    return 0;
}
```
