---
id: 761
lang: en
translation_of: index.md
source_sha256: b57d35cce6edde15c4583e2e527058f04acb6d47d5879e88a9d0001fc0d42a80
title: "POJ2891: Strange Way to Express Integers — Solution"
description: "A system of linear congruences whose moduli need not be coprime, solved by merging the equations one at a time with exgcd."
tags: ["OI","Math","Number Theory","exgcd","Congruence Equations"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The author's formulas are kept as written, including the incomplete product m=\\prod_{i=1}^{k-1} and “find k” (presumably t); neither was corrected."
---

## Approach

Well, for a math <span class="slang" data-zh="菜鸡" data-gloss="càijī, “vegetable chicken”. Slang for a noob, someone who is bad at something; self-deprecating here.">scrub</span> like me, writing math problems really is a miserable experience.

First, analyzing the problem: it obviously gives some linear congruences and asks us to solve them. But unlike with the Chinese Remainder Theorem, this problem does not guarantee that the moduli are coprime.

$$
\begin{gathered} x \equiv a_1 (mod\ m_1) \\ x \equiv a_2 (mod\ m_2) \\ x \equiv a_3 (mod\ m_3) \\ \dots \\ x \equiv a_i (mod\ m_i) \end{gathered}
$$

But we can still solve this with the good old extended Euclidean algorithm: just merge the equations.

Suppose we are solving the $k$-th equation. Let $m=\prod_{i=1}^{k-1}$, and let $x$ be a solution satisfying equations $1$~$k-1$. We know that $tm+x$ is the general solution of the first $k-1$ equations, so in this round we only need to find $k$ and update the answer, that is, solve:

$$
\begin{gathered} tm_{k-1} + x_{k-1} \equiv a_k(mod\ m_k) \\ tm_{k-1} + m_k y \equiv a_k - x_{k-1}(mod\ m_k) \end{gathered}
$$

Just plug it into $exgcd$ and solve it.

## Code

```cpp
// POJ2891.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 1e6 + 200;
ll exgcd(ll a, ll b, ll &x, ll &y)
{
    if (b == 0)
    {
        x = 1, y = 0;
        return a;
    }
    ll d = exgcd(b, a % b, x, y), z = x;
    x = y, y = z - (a / b) * y;
    return d;
}
int main()
{
    ll n;
    while (~scanf("%lld", &n))
    {
        ll x, y, a, b, k;
        scanf("%lld%lld", &a, &b);
        ll lcm = a, ans = b;
        bool flag = true;
        n--;
        while (n--)
        {
            scanf("%lld%lld", &a, &b);
            b = (b - ans % a + a) % a;
            ll d = exgcd(lcm, a, x, y);
            if (b % d)
                flag = false;
            else
                k = x * (b / d);
            ans += k * lcm;
            lcm = lcm / d * a;
            ans = (ans % lcm + lcm) % lcm;
        }
        if (flag)
            printf("%lld\n", ans);
        else
            puts("-1");
    }
    return 0;
}
```
