Sequence GCD WGCD Solution Codechef

Codechef Sequence GCD WGCD Solution

You are given an integer sequence A=(A1,A2,…,AN) of length N and an integer M such that 0≤M<∑i=1NAi.

An integer sequence B=(B1,B2,…,BN) of length N is called good if:

  • 0≤Bi≤Ai for each 1≤i≤N
  • B1+B2+⋯+BN=M

Find the maximum value of gcd(A1−B1,A2−B2,…,AN−BN) over all good sequences B. Here, gcd denotes the greatest common divisor.

Note: gcd(a,b,c)=gcd(a,gcd(b,c)) and gcd(a,0)=gcd(0,a)=a.

Input Format

  • The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follows.
  • The first line of each test case contains two space-separated integers N,M.
  • The second line of each test case contains N space-separated integers A1,A2,…,AN.

Output Format

For each test case, print a single line containing one integer — the maximum value of gcd(A1−B1,A2−B2,…,AN−BN) over all good sequences B.

Constraints

  • 1≤T≤10
  • 1≤N≤105
  • 1≤Ai≤105
  • 0≤M<∑i=1NAi

Subtasks

Subtask #1 (50 points): 1≤N≤104

Subtask #2 (50 points): Original constraints

Sample Input 1

4
4 4
1 3 5 7
4 4
5 5 5 5
4 0
4 6 9 12
6 10
15 9 3 8 14 17

Sample Output 1

3
4
1
7

Explanation

Test case 1: The optimal strategy is to take B=(1,0,2,1). The answer is gcd(1−1,3−0,5−2,7−1)=gcd(0,3,3,6)=3.

Test case 2: The optimal strategy is to take B=(1,1,1,1). The answer is gcd(5−1,5−1,5−1,5−1)=gcd(4,4,4,4)=4.

SOLUTION

Program: Codechef Sequence GCD WGCD Solution in C++

// Efficient C++ program to find length of
// the largest subsequence with GCD greater
// than 1.
#include<bits/stdc++.h>
using namespace std;

#define MAX 1000001


int prime[MAX];


void SieveOfEratosthenes()
{
	for (int i = 2; i * i < MAX; ++i)
	{
		if (!prime[i])
			for (int j = i * i; j < MAX; j += i)
				prime[j] = i;
	}

	// Prime number will have same divisor
	for (int i = 1; i < MAX; ++i)
		if (!prime[i])
			prime[i] = i;
}

// Returns length of the largest subsequence
// with GCD more than 1.
int largestGCDSubsequence(int arr[], int n ,int countdiv[])
{
	int ans = 0;
	for (int i=0; i < n; ++i)
	{
		int element = arr[i];

		// Fetch total unique prime divisor of element
		while (element > 1)
		{
			int div = prime[element];

		
			++countdiv[div];

			
			ans = max(ans, countdiv[div]);

			while (element % div==0)
				element /= div;
		}
	}

	return ans;
}

// Driver code
int main()
{
	// Pre-compute smallest divisor of all numbers
	SieveOfEratosthenes();

	int t;
	cin>>t;
	while(t--)
	{
	    int n;
	    cin>>n;
	    int a[1000001];
	   int countdiv[1000001]={0};
	    for(int i=0;i<n;i++)
	    cin>>a[i];
	    cout<<largestGCDSubsequence(a,n,countdiv)<<"\n";
	}
}

February Long 2022 – II (Rated for Div 3)

Leave a Comment

8 + six =