For $10\%$ of the test cases, it's guaranteed that $n,m\le 10^3$.
For another $20\%$, $M$ is a prime.
For another $20\%$, $M$ is a power of $2$.
For $100\%$ of the test cases, it's guaranteed that $0\le n, m\le 10^5, 2\le M\le 10^9, 0\le a_i, b_j < M$.