Count number of sub-sequences with GCD 1 in C++


We are given an array of integer elements and the task is to find the sub-sequences from the given array which are having GCD as 1. GCD is the greatest common divisor of two or more integers that divides the given numbers entirely and greatest amongst all.

Input − int arr[] = {3, 4, 8, 16}

Output − Count of number of sub-sequences with GCD 1 are − 7

Explanation

The sub-sequences that can be formed from the given array with GCD as 1 are (3, 4), (3, 8), (3, 16), (4, 3), (8, 3), (16, 3), (3, 4, 8)

Input − int arr[] = {5, 7, 10}

Output − Count of number of sub-sequences with GCD 1 are − 3

Explanation

The sub-sequences that can be formed from the given array with GCD as 1 are (5, 7), (7, 10), (5, 7, 10)

Approach used in the below program is as follows

  • Input an array of integer elements of any given size.

  • Calculate the size of an array and pass the data to the function for further processing

  • Declare a temporary variable count to store the count of sub-sequences with GCD as 1

  • Start loop FOR from i to 0 till the size of an array

  • Inside the loop start another loop FOR from j to 0 till the size of an array

  • Inside the loop, check IF GCD(arr[i], arr[j]) = TRUE then increment the count by 1

  • Return count

  • Print the result.

Example

 Live Demo

# include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b){
   if (a == 0)
      return b;
   return gcd(b % a, a);
}
int GCD_1(int arr[],int size){
   int count = 0;
   for(int i=0;i<size;i++){
      for(int j=0;j<=size;j++){
         if(gcd(arr[i],arr[j])==1){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = {3, 4, 8, 16};
   int size = sizeof(arr)/sizeof(arr[0]);
   cout<<"Count of number of sub-sequences with GCD 1 are: "<<GCD_1(arr, size);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of number of sub-sequences with GCD 1 are: 7

Updated on: 31-Aug-2020

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements