// C# program to implement
// the above approach
using System;
class GFG
{
// Function to find index of the last
// element which is divisible the given element
static int binSearch(int[] g, int st, int en, int val)
{
// Initially assume the
// index to be -1
int ind = -1;
while (st <= en)
{
// Find the mid element
// of the subarray
int mid = st + (en - st) / 2;
// If the mid element is divisible by
// given element, then move to right
// of mid and update ind to mid
if (g[mid] % val == 0)
{
ind = mid;
st = mid + 1;
}
// Otherwise, move to left of mid
else
{
en = mid - 1;
}
}
// Return the length of prefix
return ind + 1;
}
// Recursive function to return
// gcd of a and b
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
// Function to compute and print for each query
static void solveQueries(int[] arr, int[] queries,
int n, int q)
{
int[] g = new int[n];
// Pre compute the gcd of the prefixes
// of the input array in the array g[]
for (int i = 0; i < n; i++)
{
if (i == 0)
{
g[i] = arr[i];
}
else
{
g[i] = gcd(g[i - 1], arr[i]);
}
}
// Perform binary search
// for each query
for (int i = 0; i < q; i++)
{
Console.Write(binSearch(g, 0, n - 1,
queries[i]) + " ");
}
}
// Driver code
public static void Main()
{
// Given array
int[] arr = { 12, 6, 15, 3, 10 };
// Size of array
int n = arr.Length;
// Given Queries
int[] queries = { 4, 3, 2 };
// Size of queries
int q = queries.Length;
solveQueries(arr, queries, n, q);
}
}
// This code is contributed by susmitakundugoaldanga