This page is still under construction.

Parts of this page are still being built. What you see may change.

Arithmetic Sequence and Queries

Time limit2sMemory limit512 MB

Summary
Given an arithmetic sequence with first term a and difference d, answer queries for the sum or the gcd of a contiguous range of terms.
Level

Medium6 of 10

Topics
Math, Number theory, Prefix sum, Implementation
Solved
No attempts yet

Problem

An arithmetic sequence is a sequence in which the difference between consecutive terms is constant. For two consecutive terms, the value obtained by subtracting the earlier term from the later term is called the common difference. You are given an arithmetic sequence whose first term is aa and whose common difference is dd. Let AiA_i be the ii-th element of the sequence. Write a program that processes the following queries.

  • 1 l r : Print the sum of Al,Al+1,...,ArA_l, A_{l+1}, ... , A_r.
  • 2 l r : Print the greatest common divisor of Al,Al+1,...,ArA_l, A_{l+1}, ... , A_r. This is the largest positive integer among the common divisors of Al,Al+1,...,ArA_l, A_{l+1}, ... , A_r.

Input

The first line gives the first term aa and the common difference dd of the sequence.

The second line gives the number of queries qq.

Each of the next qq lines gives one query.

Output

For each query, print the answer on its own line.

Constraints

  • 1≤a≤1061 ≤ a ≤ 10^6, 0≤d≤1060 ≤ d ≤ 10^6
  • 1≤q≤1061 ≤ q ≤ 10^6
  • 1≤l≤r≤1061 ≤ l ≤ r ≤ 10^6

Examples2

  1. Example 1

    Input
    4 2
    3
    1 1 1
    1 1 2
    2 1 2
    
    Expected output
    4
    10
    2
    
  2. Example 2

    Input
    5 3
    2
    1 2 5
    2 3 6
    
    Expected output
    50
    1