Under construction

Still being built. Things may change

Fancy Formulas

Time limit2sMemory limit512 MB

Summary
Given a prime p and pairs (a,b) with a+b not divisible by p, find the minimum number of operations to transform one pair into another, or report impossibility.
Level

Hard8 of 10

Topics
Math, Number theory, Graph, BFS
Solved
No attempts yet

Problem

You are given a prime pp and a pair of integers (a,b)(a, b) such that their sum is not divisible by pp. In one operation, you can do one of the following:

  • Replace (a,b)(a, b) with (2a mod p,(b+p−a) mod p)(2a \bmod p, (b+p-a) \bmod p)
  • Replace (a,b)(a, b) with ((a+p−b) mod p,2b mod p)((a+p-b) \bmod p, 2b \bmod p)

You have to answer qq queries. In the ii-th query, find the smallest number of operations needed to transform the pair (ai,bi)(a_i, b_i) into the pair (ci,di)(c_i, d_i), or determine that it is impossible.

Note that the order of numbers matters. For example, for p=3p = 3, the distance between (1,2)(1, 2) and (2,1)(2, 1) is 11, not 00.

Input

The first line contains two integers pp and qq (2≤p≤109+72 \le p \le 10^9 + 7, pp is prime, 1≤q≤1051 \le q \le 10^5): the prime and the number of queries to answer.

The ii-th of the next qq lines contains four integers aia_i, bib_i, cic_i, did_i (0≤ai,bi,ci,di<p0 \le a_i, b_i, c_i, d_i < p, and ai+bia_i+b_i is not divisible by pp).

Output

For each query, if it is impossible to transform (ai,bi)(a_i, b_i) into (ci,di)(c_i, d_i), output −1-1. Otherwise, output the smallest number of operations required to achieve this goal.

Examples1

  1. Example 1

    Input
    5 10
    2 1 3 0
    2 1 4 4
    1 3 4 0
    0 2 0 4
    3 3 1 2
    0 1 0 1
    0 3 0 3
    0 1 0 1
    1 2 4 4
    1 0 1 1
    
    Expected output
    2
    1
    2
    -1
    -1
    0
    0
    0
    1
    -1