Problem Description
Alex has invented a new game for fun. There are n integers at a board and he performs the following moves repeatedly:
- He chooses three numbers a, b and c written at the board and erases them.
- He chooses two numbers from the triple a, b and c and calculates their greatest common divisor, getting the number d (d maybe gcd(a,b), gcd(a,c) or gcd(b,c)).
- He writes the number d to the board two times.
It can be seen that after performing the move n−2 times, there will be only two numbers with the same value left on the board. Alex wants to know which numbers can left on the board possibly. Can you help him?
Input
There are multiple test cases. The first line of input contains an integer T (1≤T≤100), indicating the number of test cases. For each test case:
The first line contains an integer n (3≤n≤500) – the number of integers written on the board. The next line contains n integers: a1,a2,…,an (1≤ai≤1000) – the numbers on the board.
Output
For each test case, output the numbers which can left on the board in increasing order.
Sample Input
3
4
1 2 3 4
4
2 2 2 2
5
5 6 2 3 4
Sample Output
1 2
2
1 2 3
Source
BestCoder Round #87
n个数每次选三个数删除,取其中两个数将gcd放回去两次,问最后剩的数可能是多少。
a,b,c,d,e,f,g,h
取a,b,c那么gcd(a, b) = d,丢掉c,最后得到d,d,e,f,g,h
取d,d,e的时候选gcd(d,d)=d丢掉e的……也可能gcd(d,e)=x丢掉d,那么d,和x都有可能。。
所以先取出数两两得到gcd后,再用gcd与每个数去gcd知道不变或这n-3次。之后。
注意:需要跑n - 3次,因为第一步的操作相当于去掉了3个元素,然后把gcd的初始信息存储在g中了,
多了的话就有可能计算出n个数的gcd了,但最多只能是n - 1个的,因为无论如何第一步操作会直接丢弃一个数
#include<bits/stdc++.h>
using namespace std;
#define LL long long
int g[1005];
int a[1005];
int main(){
int t,n;
cin>>t;
while(t-->0){
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
memset(g,0,sizeof(g));
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
g[__gcd(a[i],a[j])]=1;
}
}
int flag=1,cnt=1;
while(flag&&cnt<=n-3){
cnt++;
flag=0;
for(int i=1;i<=1000;i++){
if(g[i]){
for(int j=1;j<=n;j++){
int temp=__gcd(a[j],i);
if(g[temp]==0){
flag=1;
g[temp]=1;
}
}
}
}
}
bool first=true;
for(int i=1;i<=1000;i++){
if(g[i]!=0){
if(first){
cout<<i;
first=false;
}
else cout<<" "<<i;
}
}
cout<<endl;
}
return 0;
}