arc108_a - Sum And Product
23 Nov 2020 — Tags: math,brute_force — URL- Write both equations in terms of one variable, N or M: $N^2 - NS + P = 0$.
- The problem reduces to finding a positive root of that expression.
- This problem could be solved by doing a binary search, but it would result in integer overflow.
- Note, however, that $\max(N, M) <= \sqrt{max(S, P)}$.
- Since that value doesn’t exceed $10^6$, we can linear search the answer.
Time complexity: $O( \sqrt{ \max(S, P)})$
Memory complexity: $O(1)$
Click to show code.
using namespace std;
using ll = long long;
using predicate = function<bool(ll)>;
bool solve(ll S, ll P)
{
for (ll N = 1, MAX = 1e6; N <= MAX; ++N)
if (N * (S - N) == P)
return true;
return false;
}
int main(void)
{
ios::sync_with_stdio(false), cin.tie(NULL);
ll S, P;
cin >> S >> P;
cout << (solve(S, P) ? "Yes" : "No") << endl;
return 0;
}