A. Bestie

A. Bestie
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given an array aa consisting of nn integers a1,a2,,ana1,a2,…,an. Friends asked you to make the greatest common divisor (GCD) of all numbers in the array equal to 11. In one operation, you can do the following:

  • Select an arbitrary index in the array 1in1≤i≤n;
  • Make ai=gcd(ai,i)ai=gcd(ai,i), where gcd(x,y)gcd(x,y) denotes the GCD of integers xx and yy. The cost of such an operation is ni+1n−i+1.

You need to find the minimum total cost of operations we need to perform so that the GCD of the all array numbers becomes equal to 11.

Input

Each test consists of multiple test cases. The first line contains an integer tt (1t50001≤t≤5000) — the number of test cases. The description of test cases follows.

The first line of each test case contains a single integer nn (1n201≤n≤20) — the length of the array.

The second line of each test case contains nn integers a1,a2,,ana1,a2,…,an (1ai1091≤ai≤109) — the elements of the array.

Output

For each test case, output a single integer — the minimum total cost of operations that will need to be performed so that the GCD of all numbers in the array becomes equal to 11.

We can show that it's always possible to do so.

input

9
1
1
1
2
2
2 4
3
3 6 9
4
5 10 15 20
5
120 60 80 40 80
6
150 90 180 120 60 30
6
2 4 6 9 12 18
6
30 60 90 120 125 125

output

0
1
2
2
1
3
3
0
1

题解

#include <iostream>
#include <cstring>
using namespace std;
const int N=30;
int t,n;
int a[N];
int gcd(int x,int y){
    return y? gcd(y,x%y):x;
}
int main(){
    cin>>t;
    while(t--){
        cin>>n;
        for(int i=1;i<=n;i++){
            cin>>a[i];
        }
        if(n==1){//当n=1,只有两种情况元素为1或者不为1 
            if(a[1]==1) cout<<0<<endl;
            else cout<<1<<endl;
            continue; 
        }
        if(n==2){//一共三种情况,因为a[1]和1的最大公约数一定为1 
            if(gcd(a[1],a[2])==1) cout<<0<<endl;
            else if(gcd(a[1],gcd(a[2],2))==1) cout<<1<<endl;
            else cout<<2<<endl;
            continue;
        }
        int x=a[1];//我们发现相邻的两个下标之间一定是互质的,即如果同时改变第n-1和第n,则得到的两个数的最大公约数一定为1
        //因此当n>2时所有的花费最多不超过3 
        for(int i=2;i<n-1;i++){//求前n个数的最大公约数 
            x=gcd(x,a[i]);
        }
        //分情况讨论,如果所有的数字的最大公约数为1就无需花费 
        if(gcd(x,gcd(a[n-1],a[n]))==1) cout<<0<<endl;
        //否则看花费为1的 
        else if(gcd(gcd(x,a[n-1]),gcd(a[n],n))==1) cout<<1<<endl;
        //然后看花费为2的 
        else if(gcd(gcd(x,a[n]),gcd(a[n-1],n-1))==1) cout<<2<<endl;
        //接下来都是花费为3的 
        else cout<<3<<endl;
        
    }
}

 

posted @ 2022-10-31 08:45  突破铁皮  阅读(56)  评论(0编辑  收藏  举报