ในส่วนนี้เราจะเห็นปัญหาอื่นที่น่าสนใจ สมมติว่าเรามีอาร์เรย์ขององค์ประกอบ N เราต้องหาจุดตัดกันจำนวนขั้นต่ำเพื่อทำให้อาร์เรย์นี้เป็นอาร์เรย์แบบ co-prime ในอาร์เรย์ co-prime gcd ของทุกๆ สององค์ประกอบที่ต่อเนื่องกันคือ 1 เราต้องพิมพ์อาร์เรย์ด้วย
สมมติว่าเรามีองค์ประกอบเช่น {5, 10, 20} นี่ไม่ใช่อาร์เรย์ไพรม์ร่วม ตอนนี้การแทรก 1 ระหว่าง 5, 10 และ 10, 20 จะเป็นอาร์เรย์ co-prime ดังนั้นอาร์เรย์จะเป็นเช่น {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