Description
You are given an array of n elements, you must make it a co-prime array in as few moves as possible.
In each move you can insert any positive integral number you want not greater than 109 in any place in the array.
An array is co-prime if any two adjacent numbers of it are co-prime.
In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.
Input
The first line contains integer n (1 ≤ n ≤ 1000) — the number of elements in the given array.
The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.
Output
Print integer k on the first line — the least number of elements needed to add to the array a to make it co-prime.
The second line should contain n + k integers aj — the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by addingk elements to it.
If there are multiple answers you can print any one of them.
Sample Input
3 2 7 28
1 2 7 9 28
题意:给一个序列,要求相邻的两个数互质;
思路:用GCD来求出它们的最大公约数,如果为1,则互质,如果不唯一,就往里面添加一个数,使相邻两个数互质,不要忘记两个数相等的情况,最直接的写法就是在中间添加个1.
#include<cstdio> #include<cstring> #include<algorithm> #define size 1000000 using namespace std; int b[size]; int GCD(int x,int y) { if(x%y==0) return y; return GCD(y,x%y); } int main() { int n,a[1100],i,j,p,h,g; while(scanf("%d",&n)!=EOF) { int ans=0;p=0; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=1;i<n;i++) { if(GCD(a[i],a[i-1])==1) { b[p++]=a[i-1]; // continue; } else if(a[i]==a[i-1]) { ans++; b[p++]=a[i-1]; b[p++]=1; } else { h=max(a[i],a[i-1]);g=min(a[i],a[i-1]);//比较一下大小
for(j=g;j<h;j++) { if(GCD(a[i-1],j)==1&&GCD(j,a[i])==1) { ans++; b[p++]=a[i-1]; b[p++]=j; break; } } } } b[p++]=a[n-1]; printf("%d\n",ans); for(i=0;i<p;i++) if(i!=p-1) printf("%d ",b[i]); else printf("%d\n",b[i]); } return 0; }