Subarray GCD

来源:互联网 发布:linux 当前时间 编辑:程序博客网 时间:2024/06/09 17:38

Problem E: Subarray GCD

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 63  Solved: 32
[Submit][Status][Web Board]

Description

Given an array A1,A2...AN, you have to print the size of the largest contiguous subarray such that
GCD of all integers in that subarray is 1.

Formally,
For a subarray Ai,Ai+1...Aj where 1 ≤ i < j ≤ N to be valid: GCD(Ai,Ai+1...Aj) should be 1. You have to print the size of the largest valid subarray.

If no valid subarray exists, output -1.

Note:A single element is not considered as a subarray according to the definition of this problem.

Input

First line contains T, the number of testcases. Each testcase consists of N in one line followed by Nintegers in the next line.

Constraints

  • 1 ≤ T ≤ 10
  • 2 ≤ N ≤ 105
  • 1 ≤ Ai ≤ 105

Output

For each testcase, print the required answer in one line.

Sample Input

227 232 2 4

Sample Output

2-1

HINT

其实自己举几个案例就很清楚了,答案要么就是整个数据的长度,要么就不存在输出-1;

无非两种情况

1.      2,4,6,8........这一种情况,即存在不为1的最大公约数,直接输出-1;

2.      2,4,6,7........ 这种情况下,不要想糊涂了,公约数为2的最长为3 公约数为1的最长为4,因为1是所有数字的约数,所以只要出现不是倍数关系的,答案就位整个数据的长度

#include<cstdio>#include<cstring>#include<cctype>#include<algorithm>#include<set>#include<cstring>#include<string>#include<iostream>#include<cmath>#include<map>#include<vector>#include<stack>using namespace std;int gcd(int a,int b){    return b==0?a:gcd(b,a%b);}int main(){    int t;    scanf("%d",&t);    while(t--){        int n;        scanf("%d",&n);        int tmp=0,tmp1=0;        scanf("%d",&tmp);        for(int i=0;i<n-1;i++){            scanf("%d",&tmp1);            tmp=gcd(tmp,tmp1);        }        if(tmp==1)            printf("%d\n",n);  //直接判断最后的所有元素的最大公约数是不是1即可        else            printf("-1\n");     }    return 0;}


原创粉丝点击