在C ++中制作互素数组的最小插入
在本节中,我们将看到另一个有趣的问题。假设我们有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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短