atcoder#ABC254F. [ABC254F] Rectangle GCD

[ABC254F] Rectangle GCD

Score : 500500 points

Problem Statement

You are given a positive integer NN and sequences of NN positive integers each: A=(A1,A2,,AN)A=(A_1,A_2,\dots,A_N) and B=(B1,B2,,BN)B=(B_1,B_2,\dots,B_N).

We have an N×NN \times N grid. The square at the ii-th row from the top and the jj-th column from the left is called the square (i,j)(i,j). For each pair of integers (i,j)(i,j) such that 1i,jN1 \le i,j \le N, the square (i,j)(i,j) has the integer Ai+BjA_i + B_j written on it. Process QQ queries of the following form.

  • You are given a quadruple of integers h1,h2,w1,w2h_1,h_2,w_1,w_2 such that 1h1h2N,1w1w2N1 \le h_1 \le h_2 \le N,1 \le w_1 \le w_2 \le N. Find the greatest common divisor of the integers contained in the rectangle region whose top-left and bottom-right corners are (h1,w1)(h_1,w_1) and (h2,w2)(h_2,w_2), respectively.

Constraints

  • 1N,Q2×1051 \le N,Q \le 2 \times 10^5
  • 1Ai,Bi1091 \le A_i,B_i \le 10^9
  • 1h1h2N1 \le h_1 \le h_2 \le N
  • 1w1w2N1 \le w_1 \le w_2 \le N
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN QQ

A1A_1 A2A_2 \dots ANA_N

B1B_1 B2B_2 \dots BNB_N

query1\mathrm{query}_1

query2\mathrm{query}_2

\vdots

queryQ\mathrm{query}_Q

Each query is in the following format:

h1h_1 h2h_2 w1w_1 w2w_2

Output

Print QQ lines. The ii-th line should contain the answer to queryi\mathrm{query}_i.

3 5
3 5 2
8 1 3
1 2 2 3
1 3 1 3
1 1 1 1
2 2 2 2
3 3 1 1
2
1
11
6
10

Let Ci,jC_{i,j} denote the integer on the square (i,j)(i,j).

For the 11-st query, we have C1,2=4,C1,3=6,C2,2=6,C2,3=8C_{1,2}=4,C_{1,3}=6,C_{2,2}=6,C_{2,3}=8, so the answer is their greatest common divisor, which is 22.

1 1
9
100
1 1 1 1
109