CH3101: Factorial Decomposition — Solution
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.
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:
// 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;
}