Number of subarrays with GCD equal to 1
Last Updated :
08 Mar, 2022
Given an array arr[], the task is to find the number of sub-arrays with a GCD value equal to 1.
Examples:
Input: arr[] = {1, 1, 1}
Output: 6
All the subarrays of the given array
will have GCD equal to 1.
Input: arr[] = {2, 2, 2}
Output: 0
Approach: The key observation is that if the GCD of all the elements of the sub-array arr[l…r] is known then the GCD of all the elements of the sub-array arr[l…r+1] can be obtained by simply taking the GCD of the previous sub-array with arr[r + 1].
Thus, for every index i, keep iterating forward and compute the GCD from index i to j and check if it’s equal to 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntSubArr( int * arr, int n)
{
int ans = 0;
for ( int i = 0; i < n; i++) {
int curr_gcd = 0;
for ( int j = i; j < n; j++) {
curr_gcd = __gcd(curr_gcd, arr[j]);
ans += (curr_gcd == 1);
}
}
return ans;
}
int main()
{
int arr[] = { 1, 1, 1 };
int n = sizeof (arr) / sizeof ( int );
cout << cntSubArr(arr, n);
return 0;
}
|
Java
class GFG
{
static int cntSubArr( int []arr, int n)
{
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
int curr_gcd = 0 ;
for ( int j = i; j < n; j++)
{
curr_gcd = __gcd(curr_gcd, arr[j]);
ans += (curr_gcd == 1 ) ? 1 : 0 ;
}
}
return ans;
}
static int __gcd( int a, int b)
{
if (b == 0 )
return a;
return __gcd(b, a % b);
}
public static void main(String []args)
{
int arr[] = { 1 , 1 , 1 };
int n = arr.length;
System.out.println(cntSubArr(arr, n));
}
}
|
Python3
from math import gcd
def cntSubArr(arr, n) :
ans = 0 ;
for i in range (n) :
curr_gcd = 0 ;
for j in range (i, n) :
curr_gcd = gcd(curr_gcd, arr[j]);
ans + = (curr_gcd = = 1 );
return ans;
if __name__ = = "__main__" :
arr = [ 1 , 1 , 1 ];
n = len (arr);
print (cntSubArr(arr, n));
|
C#
using System;
class GFG
{
static int cntSubArr( int []arr, int n)
{
int ans = 0;
for ( int i = 0; i < n; i++)
{
int curr_gcd = 0;
for ( int j = i; j < n; j++)
{
curr_gcd = __gcd(curr_gcd, arr[j]);
ans += (curr_gcd == 1) ? 1 : 0;
}
}
return ans;
}
static int __gcd( int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static void Main(String []args)
{
int []arr = { 1, 1, 1 };
int n = arr.Length;
Console.WriteLine(cntSubArr(arr, n));
}
}
|
Javascript
<script>
function __gcd(a, b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
function cntSubArr(arr, n)
{
var ans = 0;
for ( var i = 0; i < n; i++) {
var curr_gcd = 0;
for ( var j = i; j < n; j++) {
curr_gcd = __gcd(curr_gcd, arr[j]);
ans += (curr_gcd == 1);
}
}
return ans;
}
var arr = [1, 1, 1];
var n = arr.length;
document.write( cntSubArr(arr, n));
</script>
|
Time Complexity: O(N2log(max(arr[])) )
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...