Composite Numbers
National Olympiad — Regional round (2019 season)
Submission name: composites.cpp
Problem summary
Given a positive integer n, output an even integer x≥n with at most one more decimal digit than n, such that p²+x is composite for every odd prime p. Output 0 if no such x exists.
Input
One positive integer n.
Output
Any suitable x, or 0 if impossible.
Constraints
1 ≤ n < 10^17.
Worked example
Official sample, transcribed with whitespace restored from the PDF.
Input
13
Output
26
Solution analysis
- Arrange x≡2 modulo 3. Every odd prime other than 3 then has p²≡1 modulo 3, so p²+x is divisible by 3. Since p≥5, the resulting number exceeds 3 and is composite.
- Handle the exceptional prime p=3 by also arranging x≡1 modulo 5. Then 9+x is a multiple of 5 greater than 5. The simultaneous congruences are x≡11 modulo 15. Requiring evenness gives x≡26 modulo 30.
- Take the smallest positive member of 26,56,86,… that is at least n. It is no more than n+29. Even for a one-digit n, 26 uses only two digits; in general n+29<10^(d+1) for d≥1 apart from cases already covered by 26. Thus this construction always fits the digit allowance. For n=13, it returns the sample answer 26.
Why it works
The output is positive, even, and at least n by construction. For p≠3, 3 divides p²+x and the number exceeds 3. For p=3, 5 divides 9+x and it exceeds 5. Therefore all required numbers are composite. If n has d digits, for d=1 the output is 26, while for d≥2 it is at most n+29≤10^d+28<10^(d+1), proving the digit limit.
Watch out. The prime 3 is exceptional in the modulo-3 argument and needs the modulo-5 condition. Any suitable x is allowed; it need not be the globally smallest solution.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
using namespace std;
int main(){
long long n;
cin>>n;
long long x=26;
if(n>x){
// Move to the first member of the arithmetic progression at least n.
x+=((n-x+29)/30)*30;
}
cout<<x<<'\n';
}