在 C++ 中找到使数组作为互素数组的最小插入
在本部分中,我们将看到另一个有趣的问题。假设我们有一个 N 元素的数组。我们必须找到使该数组成为互素数组的最小交点数量。在互素数组中,任意两个连续元素的最大公约数为 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP