Editorial for Median Modulo
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Subtask 1
For subtask 1, we can store the numbers in an array, sort it, and output the
th element.
Time complexity:
Alternatively, we can use an median finding algorithm, such as
std::nth_element
in C++.
Subtask 2
Subtask 2 is created to reward solutions that are faster than but not fast enough for subtask 3 or are incorrect because of using only 32-bit integers.
Subtask 3
For subtask 3, we can perform a binary search on the answer. To count how many numbers in the sequence are less than or equal to the number we are testing, note that and there are only
different possible values of
. When
is fixed, the numbers
form an arithmetic sequence, and we can use simple math to count how many of them are small enough.
Time complexity:
Subtask 4
Subtask 4 is created to reward solutions that use some of the observations in subtask 5.
Subtask 5
For subtask 5, note that . When doing the binary search for subtask 3, this means that if the number we are testing is fairly large, we can significantly speed things up by not considering the
values that are less than the number we are testing, since we know for sure that
is small enough. If we loop across possible
values and stop when all
with this value are small enough, we can test a number
in
time instead of
. It turns out this solution is fast enough and passes subtask 5 easily, and we prove this below.
How large is the answer? If we use one of the slower solutions to print out a lot of answers for small , we can conjecture that the answer grows approximately linear in
. If the correct answer is always around
for some constant
, then the solution above takes at most
time, which would be fast enough. Upon experimenting we can realize that
appears to be around
.
It is actually fairly easy to prove a slightly weaker bound. We show that the answer is greater than , and we do this by showing that there are more than
numbers of the form
that are greater than
. When
,
, so
which takes all numbers between
and approximately
, out of which around
are larger than
. When
,
, so
which takes every other number between approximately
and approximately
, out of which around
are larger than
. Together, these already give more than
numbers that are larger than
, proving the claim and showing that the solution above is
.
Time complexity:
Remark: Repeating the proof above for more values of , we can actually calculate that
is exactly
. With a bit more work we can show that if
is the answer to the problem, then the function
is always between
and
, and is periodic with a period of
. As a hint towards why something like this should be true, note that the lowest common multiple of
is
and
.
Comments