C++ Program to check if given numbers are coprime or not


Suppose, we have n integers in an array nums. We have to find out if the numbers in the array are pairwise coprime, setwise coprime, or not coprime.

  • Two numbers nums[i] and nums[j] are said to be pairwise coprime if gcd(nums[i], nums[j]) = 1. This should hold for every number pair in the array and i < j.

  • The numbers are said to be setwise coprime if gcd(nums[i]) = 1.

  • If they are neither, we say that they are not coprime.

So, if the input is like n = 4, nums = {7, 11, 13, 17}, then the output will be the numbers are pairwise coprime.

If we check every number pair in the array, the gcd of them will always be 1.

To solve this, we will follow these steps −

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")

Example

Let us see the following implementation to get better understanding −

#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;
}

Input

4, {7, 11, 13, 17};

Output

The numbers are pairwise coprime

Updated on: 02-Mar-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements