Open In App

Find array elements that are divisible by at least one other element

Last Updated : 24 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of positive integers, count all special numbers in the array. A number is considered a special number if it is divisible by at least one other number in the same array.

Examples : 

Input : arr[] = [1, 2, 3] 
Output : 2
Explanation : 2 and 3 are divisible by 1.

Input : arr[] = [2, 3, 4, 6, 8, 9] 
Output : 4
Explanation : 2 and 3 are not divisible by any other element. Rest of the element are divisible by at least 1 element.

Input : arr[] = [3, 5, 7, 11] 
Output : 0
Explanation : All elements are relatively prime so no special number.

[Naive Approach] Brute Divisibility Test - O(n2) Time and O(1) Space

The idea is to treat each element as a candidate and check if it can be evenly divided by any other distinct element in the array. This is done by examining all its divisors—if any of those divisors (other than itself) are present in the array, the number is considered special.

C++
#include <iostream>
#include <vector>
using namespace std;

int cntSpecialNum(vector<int> &arr) {
    
    int n = arr.size();
    int cnt = 0;

    for (int i = 0; i < n; i++) {
        bool flag = false;

        // Compare the current element with every other element
        for (int j = 0; j < n; j++) {
            
            // Skip comparison with itself
            if (i == j) continue; 

            // If arr[i] is divisible by arr[j], mark it as special
            if (arr[i] % arr[j] == 0) {
                flag = true;
                
                // No need to check further once divisibility is found
                break; 
            }
        }

        if (flag) {
            cnt++;
        }
    }

    return cnt;
}

int main() {
    vector<int> arr = {2, 3, 4, 6, 8, 9};
    int cnt = cntSpecialNum(arr);
    cout << cnt << endl;
}
Java
import java.util.*;

class GfG {

    public static int cntSpecialNum(int[] arr) {
        int n = arr.length;
        int cnt = 0;

        // Iterate through each element in the array
        for (int i = 0; i < n; i++) {
            boolean flag = false;

            // Compare the current element with every other element
            for (int j = 0; j < n; j++) {
                if (i == j) continue; 

                // If arr[i] is divisible by arr[j], mark it as special
                if (arr[i] % arr[j] == 0) {
                    flag = true;
                    break;
                }
            }

            if (flag) {
                cnt++;
            }
        }

        return cnt; 
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, 4, 6, 8, 9};
        int cnt = cntSpecialNum(arr);
        System.out.println(cnt);
    }
}
Python
def cntSpecialNum(arr):
    n = len(arr)
    cnt = 0

    # Iterate through each element in the array
    for i in range(n):
        flag = False

        # Compare the current element with every other element
        for j in range(n):
            if i == j:
                continue 

            # If arr[i] is divisible by arr[j], mark it as special
            if arr[i] % arr[j] == 0:
                flag = True
                break

        # If arr[i] is a special number, increment the count
        if flag:
            cnt += 1

    return cnt

if __name__ == "__main__":
    arr = [2, 3, 4, 6, 8, 9]
    cnt = cntSpecialNum(arr)
    print(cnt)
C#
using System;

class GfG
{
    public static int cntSpecialNum(int[] arr)
    {
        int n = arr.Length;
        int cnt = 0;

        // Iterate through each element in the array
        for (int i = 0; i < n; i++)
        {
            bool flag = false;

            // Compare the current element with every other element
            for (int j = 0; j < n; j++)
            {
                // Skip comparing the element with itself
                if (i == j) continue;

                // If arr[i] is divisible by arr[j], mark it as special
                if (arr[i] % arr[j] == 0)
                {
                    flag = true;
                    break;
                }
            }

            // If arr[i] is a special number, increment count
            if (flag)
            {
                cnt++;
            }
        }

        return cnt;
    }

    public static void Main()
    {
        int[] arr = { 2, 3, 4, 6, 8, 9 };

        int cnt = cntSpecialNum(arr);

        Console.WriteLine(cnt);
    }
}
JavaScript
function cntSpecialNum(arr) {
    let n = arr.length;
    let cnt = 0;

    // Iterate through each element
    for (let i = 0; i < n; i++) {
        let isSpecial = false;

        // Compare with every other element
        for (let j = 0; j < n; j++) {
            if (i === j) continue;
            
            // Checking if the number is divible by arr[j]
            if (arr[i] % arr[j] === 0) {
                isSpecial = true;
                break;
            }
        }

        if (isSpecial) {
            cnt += 1;
        }
    }

    return cnt;
}

// Driver code
let arr = [2, 3, 4, 6, 8, 9];
let cnt = cntSpecialNum(arr);
console.log(cnt);

Output
4

[Expected Approach] Hash-Based Multiples Check

The approach checks for each number whether any of its divisors (other than itself) exist in the array using a hash map. If any divisor is found, the number is marked as special—i.e. divisible by at least one other number in the array.

Step by Step Implementation:

  • Store the frequency of each number in the array using a hash map.
  • Iterate through each number in the array:
    • Temporarily decrease its count in the hash map to avoid matching with itself.
    • For each number, iterate from 1 to √number:
      • Check if the current value divides the number.
      • If yes, check whether either of the divisors (i or number/i) exists in the map with count > 0.
      • If any such divisor is found, mark the number as special.
    • Restore the count of the current number in the map.
  • Count and return the total number of special numbers found.
C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;


int cntSpecialNum(vector<int>& arr) {
    unordered_map<int, int> freqMap;

    // Store the frequency of each element in the map
    for (int x : arr) {
        freqMap[x]++;
    }

    int specialCount = 0;

    //  Iterate through each element in the array
    for (int x : arr) {
        freqMap[x]--; 

        bool isSpecial = false;

        // Check all divisors of x
        for (int i = 1; i * i <= x; i++) {
            if (x % i == 0) {
                
                // Check if divisor i exists
                // in the array (other than current element)
                if (freqMap[i] > 0) {
                    isSpecial = true;
                    break;
                }

                // Check the paired divisor
                // x / i if it's different
                int divi = x / i;
                if (divi != i && freqMap[divi] > 0) {
                    isSpecial = true;
                    break;
                }
            }
        }

        if (isSpecial) {
            specialCount++; 
        }

        freqMap[x]++; 
    }

    return specialCount;
}

int main() {
    vector<int> arr = {2, 3, 4, 6, 8, 9};
    cout << cntSpecialNum(arr) << endl;
    return 0;
}
Java
import java.util.*;

public class GFG {
    
    public static int cntSpecialNum(int[] arr) {
        Map<Integer, Integer> freqMap = new HashMap<>();

        //  Store the frequency of each element in the map
        for (int x : arr) {
            freqMap.put(x, freqMap.getOrDefault(x, 0) + 1);
        }

        int specialCount = 0;

        //  Iterate through each element in the array
        for (int x : arr) {
            freqMap.put(x, freqMap.get(x) - 1);

            boolean isSpecial = false;

            //  Check all divisors of x
            for (int i = 1; i * i <= x; i++) {
                if (x % i == 0) {
                    // Check if divisor i exists in the array 
                    // (other than current element)
                    if (freqMap.getOrDefault(i, 0) > 0) {
                        isSpecial = true;
                        break;
                    }

                    // Check the paired divisor x / i if it's different
                    int divi = x / i;
                    if (divi != i && freqMap.getOrDefault(divi, 0) > 0) {
                        isSpecial = true;
                        break;
                    }
                }
            }

            if (isSpecial) {
                specialCount++;
            }

            freqMap.put(x, freqMap.get(x) + 1); 
        }

        return specialCount;
    }
    
    public static void main(String[] args) {
        int[] arr = {2, 3, 4, 6, 8, 9};
        System.out.println(cntSpecialNum(arr));
    }
}
Python
from collections import defaultdict
import math

# Function to count how many numbers
# are special in the array
def cntSpecialNum(arr):
    freqMap = defaultdict(int)

    # Store the frequency of each element in the map
    for x in arr:
        freqMap[x] += 1

    specialCount = 0

    # Iterate through each element in the array
    for x in arr:
        freqMap[x] -= 1

        isSpecial = False

        # Check all divisors of x
        for i in range(1, int(math.isqrt(x)) + 1):
            if x % i == 0:
                # Check if divisor i exists in the array
                if freqMap[i] > 0:
                    isSpecial = True
                    break

                # Check the paired divisor x / i if it's different
                div = x // i
                if div != i and freqMap[div] > 0:
                    isSpecial = True
                    break

        if isSpecial:
            specialCount += 1

        freqMap[x] += 1

    return specialCount


if __name__ == "__main__":
    arr = [2, 3, 4, 6, 8, 9]
    result = cntSpecialNum(arr)
    print(result)
C#
using System;
using System.Collections.Generic;

class GFG {
   
    static int cntSpecialNum(int[] arr)
    {
        Dictionary<int, int> freqMap = new Dictionary<int, int>();

        //  Store the frequency of each element in the map
        foreach (int x in arr)
        {
            if (!freqMap.ContainsKey(x))
                freqMap[x] = 0;
            freqMap[x]++;
        }

        int specialCount = 0;

        //  Iterate through each element in the array
        foreach (int x in arr)
        {
            freqMap[x]--;

            bool isSpecial = false;

            // Check all divisors of x
            for (int i = 1; i * i <= x; i++)
            {
                if (x % i == 0)
                {
                    if (freqMap.ContainsKey(i) && freqMap[i] > 0)
                    {
                        isSpecial = true;
                        break;
                    }

                    int div = x / i;
                    if (div != i && freqMap.ContainsKey(div) && freqMap[div] > 0)
                    {
                        isSpecial = true;
                        break;
                    }
                }
            }

            if (isSpecial)
            {
                specialCount++;
            }

            freqMap[x]++;
        }

        return specialCount;
    }
    
    static void Main()
    {
        int[] arr = { 2, 3, 4, 6, 8, 9 };
        Console.WriteLine(cntSpecialNum(arr));
    }
}
JavaScript
function cntSpecialNum(arr) {
    let freqMap = {};

    // Store the frequency of each element in the map
    for (let x of arr) {
        freqMap[x] = (freqMap[x] || 0) + 1;
    }

    let specialCount = 0;

    // Iterate through each element in the array
    for (let x of arr) {
        freqMap[x]--;  

        let isSpecial = false;

        //  Check all divisors of x
        for (let i = 1; i * i <= x; i++) {
            if (x % i === 0) {
                
                // Check if divisor i exists in the array
                // (other than current element)
                if ((freqMap[i] || 0) > 0) {
                    isSpecial = true;
                    break;
                }

                // Check the paired divisor x / i if it's different
                let div = x / i;
                if (div !== i && (freqMap[div] || 0) > 0) {
                    isSpecial = true;
                    break;
                }
            }
        }

        if (isSpecial) {
            specialCount++;
        }

        freqMap[x]++;  
    }

    return specialCount;
}

// Driver Code
let arr = [2, 3, 4, 6, 8, 9];
console.log(cntSpecialNum(arr));

Output
4

Time Complexity: O(n × √max(arr[i])) outer loop runs for each element O(n), and for each element, we check all its divisors (O(√x), where x is the element's value).
Auxiliary Space: O(n)


Article Tags :
Practice Tags :

Similar Reads