Farthest Coprime

2.2

4 votes
Basic Programming, GCD, Math, Number Theory
Problem

Given an array A of N integers. You are given Q queries of the following type:-

  • x : Find the farthest index say j in the array A from index x such that A[x] and A[j] are coprime. If there exists more then one index, print the smallest one. If there does not exist any such index, print 1.

Two numbers are said to be coprime if the only common factor between them is 1.

Input Format:

  • First line contains two space-separated integers N and Q
  • Next line contains N space-separated integers denoting the array A.
  • Next line contains Q space-separated integers denoting the queries.

Output Format:

Print Q space-separated integers denoting the answer to the queries.

Constraints:

1N,Q1051A[i]1031xN

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

Query 1:

  • x = 2
  • Both A[1] & A[3] are coprime to A[x].
  • Answer is 1, as 1 < 3.

Query 2:

  • x = 1
  • Only A[2] is coprime to A[x].
  • Answer is 2.
Editor Image

?