Count of integers that divide all the elements of the given array
Given an array arr[] of N elements. The task is to find the count of positive integers that divide all the array elements.
Examples:
Input: arr[] = {2, 8, 10, 6}
Output: 2
1 and 2 are the only integers that divide
all the elements of the given array.
Input: arr[] = {6, 12, 18, 12, 6}
Output: 4
Approach: We know that the maximum integer that will divide all the array elements will be the gcd of the array and all the other integers that will divide all the elements of the array will have to be the factors of this gcd. Hence, the count of valid integers will be equal to the count of factors of the gcd of all the array elements.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getCount( int a[], int n)
{
int gcd = 0;
for ( int i = 0; i < n; i++)
gcd = __gcd(gcd, a[i]);
int cnt = 0;
for ( int i = 1; i * i <= gcd; i++) {
if (gcd % i == 0) {
if (i * i == gcd)
cnt++;
else
cnt += 2;
}
}
return cnt;
}
int main()
{
int a[] = { 4, 16, 1024, 48 };
int n = sizeof (a) / sizeof (a[0]);
cout << getCount(a, n);
return 0;
}
|
Java
class GFG
{
static int calgcd( int a, int b)
{
if (b == 0 )
return a;
return calgcd(b, a % b);
}
static int getCount( int [] a, int n)
{
int gcd = 0 ;
for ( int i = 0 ; i < n; i++)
gcd = calgcd(gcd, a[i]);
int cnt = 0 ;
for ( int i = 1 ; i * i <= gcd; i++)
{
if (gcd % i == 0 )
{
if (i * i == gcd)
cnt++;
else
cnt += 2 ;
}
}
return cnt;
}
public static void main (String[] args)
{
int [] a = { 4 , 16 , 1024 , 48 };
int n = a.length;
System.out.println(getCount(a, n));
}
}
|
Python3
from math import gcd as __gcd
def getCount(a, n):
gcd = 0
for i in range (n):
gcd = __gcd(gcd, a[i])
cnt = 0
for i in range ( 1 , gcd + 1 ):
if i * i > gcd:
break
if (gcd % i = = 0 ):
if (i * i = = gcd):
cnt + = 1
else :
cnt + = 2
return cnt
a = [ 4 , 16 , 1024 , 48 ]
n = len (a)
print (getCount(a, n))
|
C#
using System;
class GFG
{
static int calgcd( int a, int b)
{
if (b == 0)
return a;
return calgcd(b, a % b);
}
static int getCount( int [] a, int n)
{
int gcd = 0;
for ( int i = 0; i < n; i++)
gcd = calgcd(gcd, a[i]);
int cnt = 0;
for ( int i = 1; i * i <= gcd; i++)
{
if (gcd % i == 0)
{
if (i * i == gcd)
cnt++;
else
cnt += 2;
}
}
return cnt;
}
public static void Main ()
{
int [] a = { 4, 16, 1024, 48 };
int n = a.Length;
Console.WriteLine(getCount(a, n));
}
}
|
Javascript
<script>
function calgcd(a, b)
{
if (b == 0)
return a;
return calgcd(b, a % b);
}
function getCount(a, n)
{
let gcd = 0;
for (let i = 0; i < n; i++)
gcd = calgcd(gcd, a[i]);
let cnt = 0;
for (let i = 1; i * i <= gcd; i++) {
if (gcd % i == 0) {
if (i * i == gcd)
cnt++;
else
cnt += 2;
}
}
return cnt;
}
let a = [ 4, 16, 1024, 48 ];
let n = a.length;
document.write(getCount(a, n));
</script>
|
Time Complexity: O(N*log(max_element))
Auxiliary Space: O(1)
Last Updated :
03 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...