Given n non-negative integers A1, A2, · · · , An. Determine if there is only one positive integer M that ∀i ∈ {1, 2, · · · , n}, Ai = 2i−1 mod M. If so, print the integer M, or print “-1”. Here, a mod b denotes the remainder of a after division by b, where a ∈ [0, b) holds. For example, 5 mod 2 = 1, 9 mod 3 = 0, 1 mod 2 = 1.
Input
The first line contains one integer T (1 ≤ T ≤ 105 ), denoting the number of test cases. For each test case: The first line contains one integer n (1 ≤ n ≤ 105 ), denoting the number of given integers. The second line contains n integers A1, A2, · · · , An (0 ≤ Ai ≤ 109 ), denoting the given integers. It is guaranteed that Pn ≤ 105 among all cases.
Output
For each test case: Output one line containing one integer, denoting the answer.
input
3
5
1 2 4 1 2
5
1 2 4 8 16
5
1 2 4 0 1
output
7
-1
-1
题意:n长度的数组A,1,2,4,8,16.....每一位模一个M对应等于Ai,求M,如果M不存在或者有多个,输出-1,否则输出M。
解析:
1.如果A1就是0的话,因为第一位是1,那么M肯定是1,那么如果存在大于0的数,那么肯定就矛盾了,因为模1都应该等于0,该情况输出-1。
2.如果A1>1,因为原始第一位是1,模上M,反而大于1,显然不符合常理,输出-1
3.遍历A数组,正常趋势是A[ i ]*2=A[ i+1],但如果发现A[ i ]*2 != A[ i+1],那么此处肯定就是模M了,被模的数=2*A[i]-A[i+1],M就等于其差值,所以此时再确定M对后面所有数都满足条件(A[i]*2%M=A[i+1]),那么就是唯一解,反之就矛盾输出-1.
#include <stdio.h>
int a[100005];
void solve()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
//第一种情况a[1]=0
if(a[1]==0)
{
for(int i=2;i<=n;i++)
{
if(a[i]>0)
{
printf("-1\n");
return;
}
}
printf("1\n");
return;
}
第二种情况a[1]!=1
if(a[1]!=1)
{
printf("-1\n");
return;
}
//正常情况
int m=-1;//初始化m,表示还没找到可行模数
for(int i=1;i<n;i++)
{
if(m==-1&&a[i]*2!=a[i+1]) m=a[i]*2-a[i+1];//m值找到,后续判断是否可行
if(m!=-1&&a[i]*2%m!=a[i+1])//m找到但是不满足条件
{
printf("-1\n");
return;
}
}
printf("%d\n",m);
}
int main()
{
int t;
scanf("%d",&t);
while(t--) solve();
return 0;
}