1. 程式人生 > 實用技巧 >Codeforces Round #657 (Div. 2) B. Dubious Cyrpto(數論)

Codeforces Round #657 (Div. 2) B. Dubious Cyrpto(數論)

題目連結:https://codeforces.com/contest/1379/problem/B

題意

給出三個正整數 $l,r,m$,判斷在區間 $[l,r]$ 內是否有 $a,b,c$ 滿足存在正整數 $n$,使得 $n \cdot a + b - c = m$ 。

題解

最容易想的一種情況是:

\begin{equation} {\lfloor \frac{m}{a} \rfloor} \cdot a + m\ \%\ a = m \end{equation}

令 $b = l + m\ \%\ a,\ c = l$ 即可。

但是當 $m<a$ 時,${\lfloor \frac{m}{a} \rfloor} = n = 0$,不滿足 $n$ 為正整數的要求,或者 $m\ \%\ a$ 較大,超出了 $[l,r]$ 區間,此時可以將原式變換為:

\begin{equation} {\lfloor \frac{m}{a} \rfloor} \cdot a + a - (a - m\ \%\ a) = m \nonumber \end{equation}

即,

\begin{equation} ({\lfloor \frac{m}{a} \rfloor} + 1) \cdot a - (a - m\ \%\ a) = m \end{equation}

因為是減去一個數,為了儘量不超出區間,令 $b = r - (a - m\ \%\ a),\ c = r$,並且此時 $n$ 一定 $\ge 1$ 。

程式碼

#include <bits/stdc++.h>
using
ll = long long; using namespace std; void solve() { ll l, r, m; cin >> l >> r >> m; for (ll a = l; a <= r; ++a) { ll b = l + m % a; ll c = l; if (m / a > 0 and l <= b and b <= r) { cout << a << ' ' << b << '
' << c << "\n"; return; } b = r - (a - m % a); c = r; if (l <= b and b <= r) { cout << a << ' ' << b << ' ' << c << "\n"; return; } } } int main() { int t; cin >> t; while (t--) solve(); }