1571: Subarray GCD
Time Limit: 1 Sec Memory Limit: 128 MB[ 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
2
2
7 2
3
2 2 4
Sample Output
2
-1
【分析】
吓人的一道题目...题意大概是给你一个序列,让你求出其中最长的gcd为1的子序列...然而...如果有一个序列的gcd是1,那不管再给这个序列加什么数...gcd依旧是1,所以这道题的答案只有2个,n或者-1,要么没有答案,要么答案序列就是整个序列
所以直接判断整个序列的gcd是不是1就可以了..是1就输出n不是1就输出01
【代码】
#include<stdio.h>
int gcd(int a,int b)
{
while (b)
{
int t=a%b;
a=b;b=t;
}
return a;
}
int main()
{
int pp;scanf("%d",&pp);
while(pp--)
{
int n;scanf("%d",&n);
int ans;scanf("%d",&ans);
int x;
for(int i=1;i<n;i++)
{
scanf("%d",&x);
ans=gcd(ans,x);
}
if(ans==1)
printf("%d\n",n);
else
printf("-1\n");
}
return 0;
}