---
id: 2283
lang: en
translation_of: index.md
source_sha256: e3706bf878b145f3e4b0a6f1a0cd96c8022a55af0d39db5e379c5ed2596f46f5
title: "min25 Sieve"
description: "Learning a new sieve again after a whole year: am I beyond saving or what?"
tags: ["OI","Math","Number Theory","Sieve","Min_25 Sieve"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The title keeps the author's spelling “min25” (the tag uses the canonical “Min_25 Sieve”)."
  - "最小值因子 (literally “smallest-value factor”) rendered as “smallest factor” throughout."
  - "质数积和 (literally “prime product sums”) is translated literally as “the product sums of the primes”, although the code maintains the sum and the count of primes."
---

## Overview

Learning a new sieve again after a whole year: am I beyond saving or what?

<!--more-->

## Main Principle

The main idea of the min25 sieve comes from the sieve of Eratosthenes: after preprocessing with a magical DP array, it can then compute the whole prefix sum in very little time. The core idea in the end is to quickly compute $f(p^k)$ to represent the multiplicative function $h(x)$ we want, so solving for $h(x)$ with the min25 sieve may require computing the prefix sums of several different $f(p^k)$ and combining them to represent $h(x)$.

First, we need to use a linear sieve to compute enough of $pre[n] = \sum_{i = 1}^n prime_i^k$. Suppose one $f(p^k)$ we now want is $f(x) = \sum_{i = 1} [i \in prime] i^k$; then we can set up a DP (don't ask me why we do this, I really have no idea how anyone came up with it).

Define $g(n, i)$ as the sum, over the first $n$ “numbers that are prime or whose smallest factor is greater than $prime_i$”, of their $k$-th powers, which you can think of as the partial result left after the sieve of Eratosthenes has run $i$ rounds. In the end, $\sum_{i = 1}^n [i \in primes] i^k = g(n, \sqrt{n})$.

At first glance, doing the DP directly gives a time complexity of $\Theta(n \sqrt n)$, but we notice that the DP's transition doesn't actually depend on $n - 1$; it transitions from $\lfloor \frac{n}{primes_i} \rfloor$ instead. So in the end there are at most $\sqrt n$ layers, while the time complexity is $\Theta(\frac{n^{\frac{3}{4}}}{\log_2 n})$, which I can't work out (zzt's paper has the proof; <span class="slang" data-zh="神仙" data-gloss="shénxiān, “immortal”. Someone, or a problem or idea, so brilliant it seems superhuman.">gods</span> can go take a look).

How do we transition? If $primes_i^2 > n$, then obviously this round of the Eratosthenes sieve sifted out nothing but air; otherwise, we need to think carefully about how to sieve out the numbers whose smallest factor is exactly $primes_i$, raised to the $k$-th power.

First, we already know that what we're sieving out is the numbers whose smallest factor is exactly $primes_i$, raised to the $k$-th power. Say one of them is $x^k$; then it can be written as $primes_i^k x'^k$. The $primes_i^k$ in front can be pulled out directly; the key is how to compute $x'^k$. We can just brute-force divide $n$ by one $primes_i$ and take $g(\lfloor \frac{n}{primes_i} \rfloor, i - 1)$.

One thing to watch out for, though: among the numbers whose smallest factor is exactly $primes_i$, raised to the $k$-th power, although dividing out $primes_i)$ gives $g(\lfloor \frac{n}{primes_i} \rfloor, i - 1)$, we also have to keep the condition “numbers whose smallest factor is exactly $primes_i$”, so we need to take $g(\lfloor \frac{n}{primes_i} \rfloor, i - 1)$ and remove from it the first $i - 1$ primes, raised to the $k$-th power, to keep the answer correct.

Putting it together:

$$
g(n, i) = \begin{cases} g(n, i - 1), primes_i^2 > n \\  g(n, i - 1) - primes_i^k (g(\lfloor \frac{n}{primes_i} \rfloor, i - 1) - pre[i - 1]) \end{cases}
$$

So you'll find that the $n$ actually gets optimized down to $\sqrt n$. We only need to store $\sqrt n$ of them.

Once this is computed, consider computing the final answer. Design a task $solve(n, nid)$, where $nid$ is the index of the smallest factor of the numbers currently being computed. First, take care of the primes' part of the answer completely, which is $g(n, maxPrimeId) - pre[nid - 1]$. Then consider the contribution of the composites: enumerate the next prime factor $primes_j$, and since the function is multiplicative, take what we get from $solve(\frac{n}{primes_j}, j + 1)$ and multiply it directly by $f(primes_j^k)$.

In summary:

$$
solve(n, nid) = g(n, maxPrimeId) - pre[nid - 1] + \sum_{j = i}^{primes_j^2 \leq n} \sum_{k = 1}^{primes_j^{k + 1} \leq n} (solve(\lfloor \frac{n}{primes_j^k} \rfloor, nid + 1) * f(primes_j^k) + f(primes_j^{k + 1}) )
$$

## Code

```cpp
// min25.cpp
// This code file is a template of min25 sieve with rich comments for easier understanding;
// This code is based on the solution of problem https://www.luogu.com.cn/problem/P5325;

// Mathematical background:
// The goal is to get {\sum_{i = 1}^n f(i), i \in [1, 10^10]}, which f(p^k) = p^k(p^k - 1).
// Of course, the function f is multiplicative function.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int MAX_N = 2e5 + 200, mod = 1e9 + 7;

// primes[] : used by linear sieve;
// primePre[] : \sum_{i = 0} [i \in prime] i;
// primePre[] : \sum_{i = 0} [i \in prime] i^2;
// idx[2][] : locations;
// facts[] & ftot : factor stored;
// g[2][] : the original g[][] with space saved;

int primes[MAX_N], tot, primePre[MAX_N], primePre2[MAX_N], idx[2][MAX_N], ftot, g[2][MAX_N];
ll facts[MAX_N];
bool vis[MAX_N];
ll n;

// helper function to locate the factor address;

struct locator
{
    int &operator[](const ll &x) { return x < MAX_N ? idx[0][x] : idx[1][n / x]; }
} loc;

int fpow(int bas, int tim)
{
    int ret = 1;
    while (tim)
    {
        if (tim & 1)
            ret = 1LL * ret * bas % mod;
        bas = 1LL * bas * bas % mod;
        tim >>= 1;
    }
    return ret;
}

const int inv2 = fpow(2, mod - 2), inv3 = fpow(3, mod - 2);

// preprocess;

void sieve()
{
    for (int i = 2; i < MAX_N; i++)
    {
        if (!vis[i])
            primes[++tot] = i, primePre[tot] = (0LL + primePre[tot - 1] + i) % mod,
            primePre2[tot] = (0LL + primePre2[tot - 1] + 1LL * i * i % mod) % mod;
        for (int j = 1; j <= tot && 1LL * i * primes[j] < MAX_N; j++)
        {
            vis[i * primes[j]] = true;
            if (i % primes[j] == 0)
                break;
        }
    }
}

int sieve(ll nbound, int nid)
{
    if (primes[nid] >= nbound)
        return 0;
    // answer would be splited into 2 parts;
    // the \sum_{i = 1} f(i) [i \in primes] part, and the rest part;
    int id = loc[nbound], nppart = 0, ppart = (0LL + g[1][id] + mod - g[0][id] + mod - (0LL + primePre2[nid] + mod - primePre[nid]) % mod) % mod;
    for (int i = nid + 1; i <= tot && 1LL * primes[i] * primes[i] <= nbound; i++)
        for (ll j = 1, acc = primes[i]; acc <= nbound; j++, acc *= primes[i])
            nppart = (0LL + nppart + 1LL * acc % mod * ((acc - 1) % mod) % mod * ((0LL + sieve(nbound / acc, i) + (j != 1)) % mod) % mod) % mod;
    return (0LL + nppart + ppart) % mod;
}

int main()
{
    scanf("%lld", &n), sieve();
    for (ll i = 1, gx; i <= n; i = gx + 1)
    {
        gx = n / (n / i);
        int id = ++ftot;
        facts[id] = n / i;
        // x^1;
        g[0][ftot] = (1LL * facts[id] % mod * ((facts[id] + 1) % mod) % mod * inv2 % mod + mod - 1) % mod;
        // x^2;
        g[1][ftot] = (1LL * facts[id] % mod * ((facts[id] + 1) % mod) % mod * inv2 % mod * (2LL * facts[id] % mod + 1) % mod * inv3 % mod + mod - 1) % mod;
        loc[facts[id]] = id;
    }
    // do dp;
    for (int i = 1; i <= tot; i++)
        for (int j = 1; j <= ftot && 1LL * primes[i] * primes[i] <= facts[j]; j++)
        {
            int pos = loc[facts[j] / primes[i]];
            g[0][j] = (0LL + g[0][j] + mod - 1LL * primes[i] * ((0LL + g[0][pos] + mod - primePre[i - 1]) % mod) % mod) % mod;
            g[1][j] = (0LL + g[1][j] + mod - 1LL * primes[i] * primes[i] % mod * ((0LL + g[1][pos] + mod - primePre2[i - 1]) % mod) % mod) % mod;
        }
    printf("%lld\n", (1LL + sieve(n, 0)) % mod);
    return 0;
}
```

## Example A: A Classic Multiplicative-Function Sieve - BZOJ 3944 Sum

First consider the prefix sums of Euler's totient function $\varphi(x)$. We find that $\varphi(p^k) = p^k - p^{k - 1} = p^{k - 1}(p - 1)$, so we only need to maintain the product sums of the primes.

Next consider the Möbius function $\mu(x)$. Here we find that the composites are surely all $0$, and the only ones that contribute are $x = \prod p_i$, so we only need to count the primes in the range, because only $\mu(p^k), k = 1$ contributes.

```cpp
// BZ3944.cpp
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int MAX_N = 2e5 + 200;

int T, primes[MAX_N], tot, idx[2][MAX_N];
ll g[2][MAX_N], pre[2][MAX_N], n, facts[MAX_N], ftot;
bool vis[MAX_N];

struct locator
{
    int &operator[](const ll &x) { return x < MAX_N ? idx[0][x] : idx[1][n / x]; }
} loc;

void sieve()
{
    for (int i = 2; i < MAX_N; i++)
    {
        if (!vis[i])
            primes[++tot] = i, pre[0][tot] = pre[0][tot - 1] + i, pre[1][tot] = -tot;
        for (int j = 1; j <= tot && 1LL * i * primes[j] < MAX_N; j++)
        {
            vis[i * primes[j]] = true;
            if (i % primes[j] == 0)
                break;
        }
    }
}

ll sieve_phi(ll nbound, int nid)
{
    if (primes[nid] >= nbound || nbound <= 1)
        return 0;
    int id = loc[nbound];
    ll ret = g[0][id] - g[1][id] - pre[0][nid] + nid;
    for (int i = nid + 1; i <= tot && 1LL * primes[i] * primes[i] <= nbound; i++)
        for (ll acc = primes[i] * primes[i], phi_acc = primes[i] - 1; acc <= nbound;)
        {
            ret += 1LL * phi_acc * sieve_phi(nbound / (acc / primes[i]), i) + phi_acc * primes[i];
            acc *= primes[i], phi_acc *= primes[i];
        }
    return ret;
}

ll sieve_mu(ll nbound, int nid)
{
    if (primes[nid] >= nbound || nbound <= 1)
        return 0;
    int id = loc[nbound];
    ll ret = -(g[1][id] - nid);
    for (int i = nid + 1; i <= tot && 1LL * primes[i] * primes[i] <= nbound; i++)
        ret -= sieve_mu(nbound / primes[i], i);
    return ret;
}

void solve()
{
    ftot = 0;
    for (ll i = 1, gx; i <= n; i = gx + 1)
    {
        gx = n / (n / i);
        int id = ++ftot;
        facts[id] = n / i;
        // prime sum & number;
        g[0][ftot] = (facts[id] + 2) * (facts[id] - 1) / 2, g[1][ftot] = facts[id] - 1;
        // prime num;
        loc[facts[id]] = id;
    }
    for (int i = 1; i <= tot; i++)
        for (int j = 1; j <= ftot && 1LL * primes[i] * primes[i] <= facts[j]; j++)
        {
            int pos = loc[facts[j] / primes[i]];
            g[0][j] -= 1LL * primes[i] * (0LL + g[0][pos] - pre[0][i - 1]);
            g[1][j] -= g[1][pos] - i + 1;
        }
    if (n == 0)
        puts("0 0");
    else
        printf("%lld %lld\n", sieve_phi(n, 0) + 1, sieve_mu(n, 0) + 1);
}

int main()
{
    scanf("%d", &T), sieve();
    while (T--)
        scanf("%lld", &n), solve();
    return 0;
}
```
