CP Notebook

← all categories

Prime Factorization eddd322c

Prime factorization via trial division. Returns factors with multiplicity, ascending. For gcd/lcm, just use std::gcd/std::lcm (<numeric>).

Time: O(\sqrt n). tested

content/math/prime-factorization.h

vector<ll> primeFactors(ll n) {
    vector<ll> factors;
    for (ll i = 2; i * i <= n; i++) {
        while (n % i == 0) {
            factors.push_back(i);
            n /= i;
        }
    }
    if (n > 1) factors.push_back(n);
    return factors;
}