求除 K 的倍数之外的所有 Array 元素的 GCD
给定一个包含N个整数的数组arr[]和一个整数K ,任务是找到除可被K整除的元素之外的所有数组元素的 GCD。
例子:
Input: arr[] = {2, 4, 6, 8, 10}, N = 5, K = 10
Output: 2
Explanation: The multiple of K is 10.
Remaining elements are 2, 4, 6 and 8 the gcd of which are 2.
Input: arr[] ={45, 15, 90, 20, 10}, N = 5, K = 15
Output: 10
方法:这个问题的基本方法是先找到K的倍数,然后找到剩余元素的GCD。
请按照以下步骤解决此问题:
- 遍历数组的所有元素
- 存储一个数组中所有不能被 K 整除的元素。
- 然后对于剩余的元素,找到所有数字的 GCD。
- 返回 GCD 值。
下面是上述方法的实现:
C++
// C++ code to implement the approach
#include
using namespace std;
// Function to print GCD
int findPrime(int arr[], int n, int k)
{
int i, hcf;
int c = 0;
// Vector used to store all the elements
// which are not divisible by k
vector v;
for (i = 0; i < n; i++) {
if (arr[i] % k == 0)
continue;
else
v.push_back(arr[i]);
}
if (v.size() == 0) {
cout << "NO";
}
else if (v.size() == 1) {
hcf = v[0];
}
else {
// Finding the gcd using built in
// funtion __gcd(value1,value2);
hcf = __gcd(v[0], v[1]);
for (i = 2; i < v.size(); i++) {
hcf = __gcd(arr[i], hcf);
}
}
return hcf;
}
// Driver Code
int main()
{
int N = 5;
int K = 10;
int arr[] = { 2, 4, 6, 8, 10 };
// Function call
cout << findPrime(arr, N, K);
return 0;
}
Python3
# Python code to implement the approach
# Function for GCD
def __gcd(a, b):
if (b == 0):
return a
return __gcd(b, a % b)
# Function to print GCD
def findPrime(arr, n, k):
c = 0
# Vector used to store all the elements
# which are not divisible by k
v = []
for i in range(n):
if (arr[i] % k == 0):
continue
else:
v.append(arr[i])
if (len(v) == 0):
print("NO")
elif (len(v) == 1):
hcf = v[0]
else:
# Finding the gcd using built in
# funtion __gcd(value1,value2);
hcf = __gcd(v[0], v[1])
for i in range(2, len(v)):
hcf = __gcd(arr[i], hcf)
return hcf
# Driver Code
N = 5
K = 10
arr = [2, 4, 6, 8, 10]
# Function call
print(findPrime(arr, N, K))
# This code is contributed by shinjanpatra
Javascript
输出
2
时间复杂度:O(N * log M),其中 M 是数组的最大元素
辅助空间:O(N)