Count of multiples in an Array before every element
Given an array arr of size N, the task is to count the number of indices j (j<i) such that a[i] divides a[j], for all valid indexes i.
Examples:
Input: arr[] = {8, 1, 28, 4, 2, 6, 7}
Output: 0, 1, 0, 2, 3, 0, 1
No of multiples for each element before itself –
N(8) = 0 ()
N(1) = 1 (8)
N(28) = 0 ()
N(4) = 2 (28, 8)
N(2) = 3 (4, 28, 8)
N(6) = 0 ()
N(7) = 1 (28)
Input: arr[] = {1, 1, 1, 1}
Output: 0, 1, 2, 3
Naive Approach: Traverse through all valid indices j, in range [0, i-1], for each index i; and count the divisors for each indexes.
Time Complexity: O(N2)
Space Complexity: O(1)
Efficient Approach: This approach is to use map. Increment the count of factors in the map while traversing the array and lookup for that count in the map to find all valid j (< i) without traversing back.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void add_factors( int n,
unordered_map< int , int >& mp)
{
for ( int i = 1; i <= int ( sqrt (n)); i++) {
if (n % i == 0) {
if (n / i == i)
mp[i]++;
else {
mp[i]++;
mp[n / i]++;
}
}
}
}
void count_divisors( int a[], int n)
{
unordered_map< int , int > mp;
for ( int i = 0; i < n; i++) {
cout << mp[a[i]] << " " ;
add_factors(a[i], mp);
}
}
int main()
{
int arr[] = { 8, 1, 28, 4, 2, 6, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
count_divisors(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void add_factors( int n,
HashMap<Integer,Integer> mp)
{
for ( int i = 1 ; i <= (Math.sqrt(n)); i++) {
if (n % i == 0 ) {
if (n / i == i) {
if (mp.containsKey(i))
mp.put(i, mp.get(i) + 1 );
else
mp.put(i, 1 );
}
else {
if (mp.containsKey(i))
mp.put(i, mp.get(i) + 1 );
else
mp.put(i, 1 );
if (mp.containsKey(n / i))
mp.put(n / i, mp.get(n / i) + 1 );
else
mp.put(n / i, 1 );
}
}
}
}
static void count_divisors( int a[], int n)
{
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for ( int i = 0 ; i < n; i++) {
System.out.print(mp.get(a[i]) == null ? 0 + " " : mp.get(a[i]) + " " );
add_factors(a[i], mp);
}
}
public static void main(String[] args)
{
int arr[] = { 8 , 1 , 28 , 4 , 2 , 6 , 7 };
int n = arr.length;
count_divisors(arr, n);
}
}
|
Python3
from collections import defaultdict
import math
def add_factors(n, mp):
for i in range ( 1 , int (math.sqrt(n)) + 1 ,):
if (n % i = = 0 ):
if (n / / i = = i):
mp[i] + = 1
else :
mp[i] + = 1
mp[n / / i] + = 1
def count_divisors(a, n):
mp = defaultdict( int )
for i in range (n) :
print (mp[a[i]], end = " " )
add_factors(a[i], mp)
if __name__ = = "__main__" :
arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ]
n = len (arr)
count_divisors(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void add_factors( int n,
Dictionary< int , int > mp)
{
for ( int i = 1; i <= (Math.Sqrt(n)); i++) {
if (n % i == 0) {
if (n / i == i) {
if (mp.ContainsKey(i))
mp[i] = mp[i] + 1;
else
mp.Add(i, 1);
}
else {
if (mp.ContainsKey(i))
mp[i] = mp[i] + 1;
else
mp.Add(i, 1);
if (mp.ContainsKey(n / i))
mp[n / i] = mp[n / i] + 1;
else
mp.Add(n / i, 1);
}
}
}
}
static void count_divisors( int []a, int n)
{
Dictionary< int , int > mp = new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
Console.Write(!mp.ContainsKey(a[i]) ? 0 + " " : mp[a[i]] + " " );
add_factors(a[i], mp);
}
}
public static void Main(String[] args)
{
int []arr = { 8, 1, 28, 4, 2, 6, 7 };
int n = arr.Length;
count_divisors(arr, n);
}
}
|
Javascript
<script>
function add_factors(n, mp)
{
for ( var i = 1; i <= parseInt(Math.sqrt(n)); i++) {
if (n % i == 0) {
if (parseInt(n / i) == i)
{
if (mp.has(i))
mp.set(i, mp.get(i)+1)
else
mp.set(i, 1)
}
else {
if (mp.has(i))
mp.set(i, mp.get(i)+1)
else
mp.set(i, 1)
if (mp.has(parseInt(n/i)))
mp.set(parseInt(n/i), mp.get(parseInt(n/i))+1)
else
mp.set(parseInt(n/i), 1)
}
}
}
return mp;
}
function count_divisors(a, n)
{
var mp = new Map();
for ( var i = 0; i < n; i++)
{
document.write( (mp.has(a[i])?mp.get(a[i]):0) + " " );
mp = add_factors(a[i], mp);
}
}
var arr = [8, 1, 28, 4, 2, 6, 7];
var n = arr.length;
count_divisors(arr, n);
</script>
|
Time Complexity: O(N * sqrt(val)), where N is the size of array and val is the maximum value of elements present in the array.
Auxiliary Space: O(N), as we are using extra space for map mp.
Approach 2: WIthout MAP:
In the code using maps, we use a defaultdict to keep track of the count of each factor for all numbers encountered so far. This allows us to avoid recomputing the factorization for each number in the input array. Instead, we can simply look up the count of factors for each element in the map and increment it as we encounter new multiples.
C++
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int count_factors( int n) {
int count = 0;
for ( int i = 1; i <= sqrt (n); i++) {
if (n % i == 0) {
if (n / i == i) {
count++;
} else {
count += 2;
}
}
}
return count;
}
void count_divisors(vector< int > a, int n) {
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = 0; j < i; j++) {
if (a[j] % a[i] == 0) {
count++;
}
}
cout << count << " " ;
}
}
int main() {
vector< int > arr {8, 1, 28, 4, 2, 6, 7};
int n = arr.size();
count_divisors(arr, n);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int countFactors( int n) {
int count = 0 ;
for ( int i = 1 ; i <= Math.sqrt(n); i++) {
if (n % i == 0 ) {
if (n / i == i) {
count++;
} else {
count += 2 ;
}
}
}
return count;
}
public static void countDivisors(List<Integer> a, int n) {
for ( int i = 0 ; i < n; i++) {
int count = 0 ;
for ( int j = 0 ; j < i; j++) {
if (a.get(j) % a.get(i) == 0 ) {
count++;
}
}
System.out.print(count + " " );
}
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList( 8 , 1 , 28 , 4 , 2 , 6 , 7 );
int n = arr.size();
countDivisors(arr, n);
}
}
|
Python3
import math
def count_factors(n):
count = 0
for i in range ( 1 , int (math.sqrt(n)) + 1 ):
if (n % i = = 0 ):
if (n / / i = = i):
count + = 1
else :
count + = 2
return count
def count_divisors(a, n):
for i in range (n):
count = 0
for j in range (i):
if a[j] % a[i] = = 0 :
count + = 1
print (count, end = " " )
if __name__ = = "__main__" :
arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ]
n = len (arr)
count_divisors(arr, n)
|
C#
using System;
using System.Collections.Generic;
namespace CountMultiples
{
class Program
{
public static int CountFactors( int n)
{
int count = 0;
for ( int i = 1; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
if (n / i == i)
{
count++;
}
else
{
count += 2;
}
}
}
return count;
}
public static void CountDivisors(List< int > a, int n)
{
for ( int i = 0; i < n; i++)
{
int count = 0;
for ( int j = 0; j < i; j++)
{
if (a[j] % a[i] == 0)
{
count++;
}
}
Console.Write(count + " " );
}
}
static void Main( string [] args)
{
List< int > arr = new List< int > { 8, 1, 28, 4, 2, 6, 7 };
int n = arr.Count;
CountDivisors(arr, n);
}
}
}
|
Javascript
function count_factors(n) {
let count = 0;
for (let i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (n / i == i) {
count++;
} else {
count += 2;
}
}
}
return count;
}
function count_divisors(a, n) {
for (let i = 0; i < n; i++) {
let count = 0;
for (let j = 0; j < i; j++) {
if (a[j] % a[i] == 0) {
count++;
}
}
console.log(count + " " );
}
}
let arr = [8, 1, 28, 4, 2, 6, 7];
let n = arr.length;
count_divisors(arr, n);
|
Time Complexity: O(sqrt(n)), where N is the size of array and val is the maximum value of elements present in the array.
Auxiliary Space: O(N)
Last Updated :
20 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...