C ++程序检查给定数字是否互质
假设我们在数组 nums 中有 n 个整数。我们必须找出数组中的数字是成对互素、成组互素还是非互素。
如果 gcd(nums[i], nums[j]) = 1,则称两个数字 nums[i] 和 nums[j] 成对互质。这应该适用于数组中的每个数字对并且 i < j。
如果 gcd(nums[i]) = 1,则称这些数字是集合互质的。
如果它们都不是,我们说它们不是互质的。
因此,如果输入类似于 n = 4, nums = {7, 11, 13, 17},那么输出将是成对互质的数字。
如果我们检查数组中的每个数字对,它们的 gcd 将始终为 1。
为了解决这个问题,我们将遵循以下步骤 -
Define an array fac of size: 100 initialized with 0s.Define an array checkPrime of size: 100 initialized with 0s.
gcdVal := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
gcdVal := gcd of (nums[i], gcdVal)
(increase fac[nums[i]] by 1)
if gcdVal is same as 1, then:
pw := true
for initialize k := 2, when k < 100, update (increase k by 1), do:
if checkPrime[k] is non-zero, then:
Ignore following part, skip to the next iteration
c := 0
for initialize j := k, when j < 100, update j := j + k, do:
c := c + fac[j]
checkPrime[j] := true
pw := pw AND true if c <= 1
if pw is non-zero, then:
print("The numbers are pairwise coprime")
Otherwise
print("The numbers are setwise coprime")
Otherwise
print("The numbers are not coprime")
示例
让我们看看以下实现以更好地理解 -
#include <bits/stdc++.h>using namespace std;
void solve(int n, int nums[]){
int fac[100] = {0};
bool checkPrime[100] = {0};
int gcdVal = 0;
for(int i = 0; i < n ; i++) {
gcdVal = __gcd(nums[i], gcdVal);
++fac[nums[i]];
}
if(gcdVal == 1) {
bool pw = true;
for(int k = 2; k < 100; ++k) {
if(checkPrime[k])
continue;
int c = 0;
for(int j = k; j < 100; j += k) {
c += fac[j];
checkPrime[j] = true;
}
pw = pw && c <= 1;
}
if(pw)
cout<< "The numbers are pairwise coprime";
else
cout<< "The numbers are setwise coprime";
}
else
cout << "The numbers are not coprime";
}
int main() {
int n = 4, nums[] = {7, 11, 13, 17};
solve(n, nums);
return 0;
}
输入
4, {7, 11, 13, 17};输出结果
The numbers are pairwise coprime
以上是 C ++程序检查给定数字是否互质 的全部内容, 来源链接: utcz.com/z/297214.html