PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: Abhinav Sharma
Testers: Nishank Suresh, Nishant Shah
Editorialist: Nishank Suresh
DIFFICULTY:
1315
PREREQUISITES:
Basic math
PROBLEM:
Given X, find if there exist any positive integer solutions to 2\cdot a + 2\cdot b + a\cdot b = X.
EXPLANATION:
Suppose we fix the value of a. Can we find out whether a valid b exists?
Yes we can
Rearrange the equation to bring b to one side, and we obtain
We want b to be a positive integer, and so all that needs to be done is to check two conditions:
- X - 2\cdot a \gt 0
- a + 2 divides X - 2\cdot a
both of which are easy to check.
With this in mind, we can iterate over all possible values of a, and check if a valid value of b exists or not.
However, there can be upto 10^9 possible values for a, and iterating over them all is too slow so we need to speed up a little.
Note that, since a\gt 0 and b\gt 0, we must have a\cdot b \leq X. In particular, this means that at least one of a and b must be no larger than \sqrt X. In particular, \min(a, b) \leq \sqrt X.
Also note that the equation is symmetric in a and b, i.e, if we swap a and b, the value of 2\cdot a + 2\cdot b + a\cdot b doesn’t change.
So, without loss of generality, we can always say that a \leq b. This, combined with our earlier observation that \min(a, b) \leq \sqrt X now gives us only \mathcal{O}(\sqrt X) different values of a that need to be checked, which is fast enough to solve the problem.
TIME COMPLEXITY
\mathcal{O}(\sqrt X) per test case.
CODE:
Editorialist's Code (Python)
for _ in range(int(input())):
x = int(input())
ans = 'no'
# b = (x - 2*a)/(a+2)
for a in range(1, x+10):
if a*a > x:
break
if 2*a >= x:
break
if (x - 2*a)%(a + 2) != 0:
continue
ans = 'yes'
break
print(ans)