在本节中,我们将看到另一个有趣的问题。假设我们有N个元素组成的数组。我们必须找到最小数量的交点才能使该数组成为互素数组。在每两个连续元素的互质数组gcd中,值为1。我们还必须打印该数组。
假设我们有{5,10,20}之类的元素。这不是互素数组。现在通过在5、10和10、20之间插入1,它将成为互素数组。所以数组就像{5,1,10,1,20}
makeCoPrime(arr, n): begin count := 0 for i in range 1 to n, do if gcd of arr[i] and arr[i – 1] is not 1, then increase count by 1 done display count value display the first element of arr for i in range 1 to n, do if gcd of arr[i] and arr[i – 1] is not 1, then display 1 display element arr[i] done end
#include <iostream> #include <algorithm> using namespace std; int makeCoPrime(int arr[], int n){ int count = 0; for(int i = 1; i<n; i++){ if(__gcd(arr[i], arr[i - 1]) != i){ count++; } } cout << "Number of intersection points: " << count << endl; cout << arr[0] << " "; for(int i = 1; i<n; i++){ if(__gcd(arr[i], arr[i - 1]) != i){ cout << 1 << " "; } cout << arr[i] << " "; } } int main() { int A[] = {2, 7, 28}; int n = sizeof(A)/sizeof(A[0]); makeCoPrime(A, n); }
输出结果
Number of intersection points: 1 2 7 1 28