/* SPDX-License-Identifier: BSD-3-Clause
 * Copyright (c) 2026 Susi Lehtola */
#include "primes.h"

/* Prime table — generated by tools/gen_prime_table.py. */
#include "prime_table.inc"

int legendre_valuation(int n, int pi)
{
    /* v_p(n!) = sum_{k>=1} floor(n / p^k) */
    int p   = g_primes[pi];
    int val = 0;
    int pk  = p;
    while (pk <= n) {
        val += n / pk;
        if (pk > n / p) break;  /* prevent overflow before multiplication */
        pk *= p;
    }
    return val;
}
