मान लीजिए, हमारे पास एक सरणी संख्या में n पूर्णांक हैं। हमें यह पता लगाना होगा कि क्या एरे में संख्याएं जोड़ीदार कोप्राइम हैं, सेटवाइज कोप्राइम हैं, या कोप्राइम नहीं हैं।
-
अगर gcd(nums[i], nums[j]) =1 दो नंबर nums[i] और nums[j] को जोड़ीवार कोप्राइम कहा जाता है। यह ऐरे में हर नंबर पेयर के लिए होना चाहिए और i
-
अगर 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