Under construction

Still being built. Things may change

Greatest of the Greatest Common Divisors

Time limit1sMemory limit2048 MB

Summary
Given an integer sequence and range queries, find the largest gcd over all pairs of positions inside each query range.
Level

Medium6 of 10

Topics
Number theory, Sorting, Array
Solved
No attempts yet

Problem

You are given a sequence of integers and a number of intervals in the sequence. The intervals are specified by their leftmost and rightmost positions. An interval consisting of kk integers has k(k−1)/2k(k - 1)/2 pairs of integers at different positions, and each pair has a greatest common divisor. For each given interval, find the greatest of these greatest common divisors.

For example, when the sequence is (a1,…,a6)=(10,20,30,40,50,60)(a_1, \dots , a_6) = (10, 20, 30, 40, 50, 60) and the whole sequence is the interval, the following 15 pairs of integers at different positions xx and yy are considered.

xx111111111122222222333333444455
yy223344556633445566445566556666
axa_x101010101010101010102020202020202020303030303030404040405050
aya_y202030304040505060603030404050506060404050506060505060606060
gcd⁡(ax,ay)\gcd(a_x,a_y)101010101010101010101010202010102020101010103030101020201010

The greatest of the greatest common divisors of these 15 pairs is gcd⁡(30,60)=30\gcd(30, 60) = 30 in this case.

Input

The input consists of a single test case. The first line contains an integer nn (2≤n≤1052 \le n \le 10^5), the number of integers in the sequence. The second line contains nn positive integers a1,…,ana_1, \dots, a_n. None of them exceeds 10510^5. The third line contains a positive integer qq (q≤105q \le 10^5), the number of intervals. The next qq lines each contain two integers lil_i and rir_i (1≤li<ri≤n1 \le l_i < r_i \le n), specifying the interval alia_{l_i} through aria_{r_i}.

Output

Output qq lines. The ii-th line contains the greatest of the greatest common divisors of all pairs in the interval specified by lil_i and rir_i.

Examples2

  1. Example 1

    Input
    6
    10 20 30 40 50 60
    3
    1 6
    2 5
    4 5
    
    Expected output
    30
    20
    10
    
  2. Example 2

    Input
    10
    13 2 35 4 13 2 5 1 7 4
    5
    1 4
    4 10
    3 8
    3 9
    1 10
    
    Expected output
    2
    4
    5
    7
    13