Given an array, count pairs in the array such that one element of pair divides other.
Examples:
Input : arr[] = {1, 2, 3}
Output : 2
The two pairs are (1, 2) and (1, 3)
Input : arr[] = {2, 3, 5, 7}
Output: 0
C++
#include <iostream>
using namespace std;
int countDivisibles( int arr[], int n)
{
int res = 0;
for ( int i=0; i<n; i++)
for ( int j=i+1; j<n; j++)
if (arr[i] % arr[j] == 0 ||
arr[j] % arr[i] == 0)
res++;
return res;
}
int main()
{
int a[] = {1, 2, 3, 9};
int n = sizeof (a) / sizeof (a[0]);
cout << countDivisibles(a, n);
return 0;
}
|
Java
class GFG {
static int countDivisibles( int arr[],
int n)
{
int res = 0 ;
for ( int i = 0 ; i < n; i++)
for ( int j = i + 1 ; j < n; j++)
if (arr[i] % arr[j] == 0 ||
arr[j] % arr[i] == 0 )
res++;
return res;
}
public static void main(String[] args)
{
int a[] = new int []{ 1 , 2 , 3 , 9 };
int n = a.length;
System.out.print(countDivisibles(a, n));
}
}
|
Python3
def countDivisibles(arr, n) :
res = 0
for i in range ( 0 , n) :
for j in range (i + 1 , n) :
if (arr[i] % arr[j] = = 0 or
arr[j] % arr[i] = = 0 ) :
res + = 1
return res
if __name__ = = '__main__' :
a = [ 1 , 2 , 3 , 9 ]
n = len (a)
print (countDivisibles(a, n) )
|
C#
using System;
class GFG {
static int countDivisibles( int []arr,
int n)
{
int res = 0;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++)
if (arr[i] % arr[j] == 0 ||
arr[j] % arr[i] == 0)
res++;
return res;
}
public static void Main(String[] args)
{
int [] a = new int [4] {1, 2, 3, 9};
int n = a.Length;
Console.Write(countDivisibles(a, n));
}
}
|
PHP
<?php
function countDivisibles( $arr , $n )
{
$res = 0;
for ( $i = 0; $i < $n ; $i ++)
for ( $j = $i + 1; $j < $n ; $j ++)
if ( $arr [ $i ] % $arr [ $j ] == 0 ||
$arr [ $j ] % $arr [ $i ] == 0)
$res ++;
return $res ;
}
$a = array (1, 2, 3, 9);
$n = count ( $a );
echo (countDivisibles( $a , $n ));
?>
|
Efficient solution for small ranged numbers.
1) Insert all elements of array in a hash table.
2) Find maximum element in the array.
3) For every array element, search multiples of it (till maximum) in the hash table. If found, increment result.
Different cases like negative numbers and repetitions can also be handled here with slight modifications to the approach.
leave a comment
0 Comments