304 North Cardinal St.
Dorchester Center, MA 02124

# Subarray GCD CodeChef Solution

## Subarray GCD CodeChef Solution in C++14

``````#include<bits/stdc++.h>
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int               long long
#define endl              "\n"
#define ppc               __builtin_popcount
#define ppcll             __builtin_popcountll
#define INF 100000000000000000
#define mod 1000000007
#define esp 10e-7
const int mx=1e5+7;
int a[mx];
void solve()
{
int n;
cin>>n;
int g=0;
for(int i=0;i<n;i++)
{cin>>a[i];
g=__gcd(g,a[i]);
}
if(g>1)
cout<<-1<<endl;
else
{
cout<<n<<endl;
}

}
signed main()
{
//#ifndef ONLINE_JUDGE
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
//freopen("error.txt" , "w" , stderr);
//#endif
IOS
int t=1,n;
cin>>t;

while(t--)
{
solve();
}

return 0;
}``````

## Subarray GCD CodeChef Solution in PYTH 3

``````# cook your dish here
import math
for _ in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
if math.gcd(*A) != 1: print(-1)
else: print(N)``````

## Subarray GCD CodeChef Solution in C

``````#include <stdio.h>

int gcd(int a, int b);

int main()
{
int t, g, i, n, x[100000];

scanf("%d",&t);

while(t--)
{
scanf("%d",&n);

for(i=0; i<n; i++)
{
scanf("%d", &x[i]);
}
for(i=0;i<n-1;i++){
g=gcd(x[i], x[i+1]);
x[i+1]=g;
}
if(g==1)printf("%d\n",n);
else printf("-1\n");

}

}
int gcd(int a, int b)
{
int rem;

while(b!=0){
rem=a%b;
a=b;
b=rem;
}
return a;
}``````

## Subarray GCD CodeChef Solution in JAVA

``````/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static int gcd(int a,int b){
if(a==0) return b;
else return gcd(b%a,a);
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t!=0){
int n=sc.nextInt();
int gcd=0;
for(int i=0;i<n;i++){
int x=sc.nextInt();
gcd=gcd(gcd,x);

}
if(gcd==1)
System.out.println(n);
else
System.out.println(-1);
t--;
}
}
}``````

## Subarray GCD CodeChef Solution in PYPY 3

``````
# Personalized for CP

# importing libraries
#from sortedcontainers import SortedList, SortedSet, SortedDict
import os
import sys
from io import BytesIO, IOBase

from sys import stdin,stdout

from bisect import bisect_left as bl,bisect_right as br

from heapq import heappush,heappop,heappushpop,nlargest,nsmallest,heapify

from collections import defaultdict,Counter,deque

from math import floor,ceil,sqrt,gcd,log2

from functools import reduce

from itertools import permutations,combinations

def lcm(a,b):

return ((a*b)//gcd(a,b))

def gcd_list(l):

x=reduce(gcd,l)

return x

def lcm_list(l):

x=reduce(lcm,l)

return x

class Node:
def __init__(self, val):
self.right = None
self.data = val
self.left = None

# Function to Build Tree
def buildTree(s):
#Corner Case
if(len(s)==0 or s[0]=="N"):
return None

# Creating list of strings from input
# string after spliting by space
ip=list(map(str,s.split()))

# Create the root of the tree
root=Node(int(ip[0]))
size=0
q=deque()

# Push the root to the queue
q.append(root)
size=size+1

# Starting from the second element
i=1
while(size>0 and i<len(ip)):
# Get and remove the front of the queue
currNode=q[0]
q.popleft()
size=size-1

# Get the current node's value from the string
currVal=ip[i]

# If the left child is not null
if(currVal!="N"):

# Create the left child for the current node
currNode.left=Node(int(currVal))

# Push it to the queue
q.append(currNode.left)
size=size+1
# For the right child
i=i+1
if(i>=len(ip)):
break
currVal=ip[i]

# If the right child is not null
if(currVal!="N"):

# Create the right child for the current node
currNode.right=Node(int(currVal))

# Push it to the queue
q.append(currNode.right)
size=size+1
i=i+1
return root
# remember to give string as parameter to buildTree Function

class BST:

#Function to search a node in BST.
def search(self, node, x):
#code here
pass

#{
#  Driver Code Starts
class Node:

def __init__(self, value):
self.left = None
self.data = value
self.right = None

class Tree:
def createNode(self, data):
return Node(data)

def insert(self, node, data):
if node is None:
return self.createNode(data)
else:
if data < node.data:
node.left = self.insert(node.left, data)
else:
node.right = self.insert(node.right, data)
return node

def traverseInorder(self, root):
if root is not None:
print(root.data, end= " ")
self.traverseInorder(root.left)
self.traverseInorder(root.right)
"""
if __name__=='__main__':
t=int(input())
for i in range(t):
n=int(input())
arr = input().strip().split()
root = None
tree = Tree()
root = tree.insert(root, int(arr[0]))
for j in range(1, n):
root = tree.insert(root, int(arr[j]))
#tree.traverseInorder(root)
num = int(input())
find = BST()
if find.search(root, num):
print(1)
else:
print(0)
"""
#To make a Binary Search Tree uncomment above

sys.setrecursionlimit(100000000)

inp    =lambda: int(input())
strng  =lambda: input().strip()
jn     =lambda x,l: x.join(map(str,l))
strl   =lambda: list(input().strip())
mul    =lambda: map(int,input().strip().split())
mulf   =lambda: map(float,input().strip().split())
seq    =lambda: list(map(int,input().strip().split()))

ceil   =lambda x: int(x) if(x==int(x)) else int(x)+1
ceildiv=lambda x,d: x//d if(x%d==0) else x//d+1

flush  =lambda: stdout.flush()
stdpr  =lambda x: stdout.write(str(x))

mod=(10**9)+7

#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

def solve():

length=inp()

arr=seq()

gc = arr[0]

for i in range(1,len(arr)):
gc = gcd(gc,arr[i])

return length  if gc==1 else -1

def main():

testcases=inp()

for test in range(testcases):

print(solve())

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
newlines = 0

def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None

while True:
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0

while self.newlines == 0:
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1

def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# endregion

if __name__ == "__main__":
main()

``````

## Subarray GCD CodeChef Solution in PYTH

``````def gcd(n, m):
r = n % m
while r > 0:
n = m
m = r
r = n % m
#endwhile
return m
#end fun
t = int(raw_input())
for i in xrange(t):
N = int(raw_input())
st = raw_input().split()
g = int(st[0])
p = 1
while (g > 1) and (p < N):
n = int(st[p])
g = gcd(n,g)
p += 1
# endwhile
if g == 1:
print N
else:
print '-1'
# endif
# endfor i
``````

## Subarray GCD CodeChef Solution in C#

``````using System;

public class Test
{
public static void Main()
{
SubarrayGCD.Run();
}

public class SubarrayGCD
{
public static void Run()
{
var solution = new Solution();

for (int t = 0; t < T; t++)
{
var res = solution.solution(A);
Console.WriteLine(res);
}
}

public class Solution
{
public int solution(int[] A)
{
Array.Sort(A);

var gcd = A[A.Length - 1];
for (int i = A.Length-2; i >= 0; i--)
{
gcd = GCD(A[i], gcd);
if (gcd == 1)
return A.Length;
}
return -1;
}

private int GCD(int a, int b)
{
if (a % b == 0)
return b;
else
return GCD(b, a % b);
}
}
}
}``````

## Subarray GCD CodeChef Solution in NODEJS

``````const readline = require('readline');

input: process.stdin,
output: process.stdout,
terminal: false
});

input = [];
rl.on('line',function(line){
input.push(line);
}).on('close',function(){
main(input);
process.exit(0);
});

function gcd(a,b){
while(a != b){
if(a > b){
a = a-b;
}else{
b = b-a;
}
}
return a;
}

function gcd_arr(arr,n){
_gcd = arr[0];
for(var i = 1; i < n; i++){
_gcd = gcd(arr[i],_gcd);
if (_gcd == 1)
return 1;
}
return _gcd;
}

function main(input){
t = parseInt(input[0],10);
offset = 0
for(var i=0; i < t; i++){
n =  input[offset+i+1];
arr = input[offset+i+2].split(" ")
.map(function(a){
return parseInt(a,10);
});
if(gcd_arr(arr,n) == 1)
console.log(arr.length);
else
console.log(-1);
offset += 1;
}
}``````
##### Subarray GCD CodeChef Solution Review:

In our experience, we suggest you solve this Subarray GCD CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Subarray GCD CodeChef Solution.

Find on CodeChef

##### Conclusion:

I hope this Subarray GCD CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!