배열 nums에 n개의 정수가 있다고 가정합니다. 배열의 숫자가 pairwise coprime인지 setwise coprime인지 아니면 coprime이 아닌지 확인해야 합니다.
-
두 숫자 nums[i] 및 nums[j]는 gcd(nums[i], nums[j]) =1인 경우 쌍별 공소수(pairwise coprime)라고 합니다. 이것은 배열의 모든 숫자 쌍과 i
-
숫자는 gcd(nums[i]) =1인 경우 setwise coprime이라고 합니다.
-
둘 다 아닌 경우, 우리는 그들이 동소가 아니라고 말합니다.
따라서 입력이 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