Open In App

Count Prime Multiples

Last Updated : 26 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an array arr[] consisting of distinct prime numbers and an integer m, find how many numbers in the range from 1 to m (inclusive) are divisible by at least one of the prime numbers in the array.

Examples:

Input : arr[] = [2, 3, 5], m = 10
Output : 8
Explanation : From 1 to 10 there are 8 number which are at least divisible by 2, 3, 5.

Input : arr[] = [2, 5, 7], m = 15
Output : 10
Explanation : From 1 to 15 there are 10 number which are at least divisible by 2, 5, 7.

Inclusion Exclusion Principle

The Inclusion-Exclusion Principle is a fundamental concept in combinatorics used to compute the size of the union of multiple sets, especially when those sets overlap.

For finite sets A1, A2, ..., An the number of elements in their union is given by:
\scriptstyle|A_1 \cup A_2 \cup \cdots \cup A_n| = \sum_{i} |A_i| - \sum_{i < j} |A_i \cap A_j| + \sum_{i < j < k} |A_i \cap A_j \cap A_k| - \sum_{i < j < k < l} |A_i \cap A_j \cap A_k \cap A_l| + \cdots

Understanding the Role of Inclusion-Exclusion in this Problem -

Imagine we define:

  • Ai ​: the set of all numbers in the range [1, m] divisible by the prime pi ∈ arr[].
  • So, we are looking for: ∣A1 ∪ A2 ∪ ⋯ ∪ An

This is the count of numbers ≤ m that are divisible by at least one prime from the array.
This union of sets is exactly the kind of thing the Inclusion-Exclusion Principle (IEP) is built to solve.

Step by Step Implementations -

  • Loop over all non-empty subsets of the given prime array.
  • For each subset, compute the product of selected primes.
  • Count how many numbers ≤ m are divisible by this product using m / product.
  • The final accumulated value is the total count of numbers divisible by at least one prime.
  • If the subset size is even, subtract the count from the answer.
  • If the subset size is odd, add the count to the answer.

Example Explanation using IEP -

Using the Inclusion-Exclusion Principle (IEP), we count numbers ≤  10 divisible by any of {2, 3, 5}.
We add individual counts: (5 + 3 + 2), subtract pairwise overlaps: -(1 +1 +0), and add the triple overlap: +(0).
Total = (5 + 3 + 2) - (1 + 1 + 0) + (0) = 8, which avoids double-counting shared multiples.

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

int countDivisible(vector<int>& arr, int m) {
    int n = arr.size();
    int odd = 0, even = 0;

    // Total subsets = 2^n (including empty set)
    int powerset = (1 << n);

    // Iterate through all non-empty subsets of primes
    for (int i = 1; i < powerset; i++) {
        int p = 1;

        // Compute the product of selected primes in this subset
        for (int j = 0; j < n; j++) {
            if (i & (1 << j)) {
                p *= arr[j];

                // If product exceeds m, break early
                if (p > m)
                    break;
            }
        }

        // If product exceeds m, skip this subset
        if (p > m)
            continue;

        // Inclusion-Exclusion:
        // - If the number of selected primes is odd, add the count
        // - If even, subtract the count
        if (__builtin_popcount(i) & 1)
            odd += (m / p);   
        else
            even += (m / p);  
    }

    // Final result based on Inclusion-Exclusion Principle
    return odd - even;
}

int main() {
    vector<int> arr = {2, 3, 5};
    int m = 10;
    cout << countDivisible(arr, m);
    return 0;
}
Java
class GfG {

    public static int countDivisible(int[] arr, int m) {
        int n = arr.length;
        int odd = 0, even = 0;

        // Total number of subsets = 2^n (excluding empty subset)
        int powerSet = 1 << n;

        for (int mask = 1; mask < powerSet; mask++) {
            int product = 1;
            // counting the number of set bit in the mask
            int bitCount = Integer.bitCount(mask);

            for (int j = 0; j < n; j++) {
                if ((mask & (1 << j)) != 0) {
                    product *= arr[j];

                    // Stop if product exceeds m
                    if (product > m)
                        break;
                }
            }

            if (product > m)
                continue;
            
            // count of numbers that are divisible by product
            int count = m / product;

            // Inclusion-Exclusion logic
            
            // odd count of 
            if (bitCount % 2 == 1)
                odd += count;
            else
                even += count;
        }

        return odd - even;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, 5};
        int m = 10;
        System.out.println(countDivisible(arr, m)); 
    }
}
Python
def countDivisible(arr, m):
    n = len(arr)
    odd = 0
    even = 0

    # Total subsets = 2^n (including empty set)
    powerSet = 1 << n

    # Iterate through all non-empty subsets of primes
    for mask in range(1, powerSet):
        product = 1
        bitCount = 0  

        # Compute the product of selected primes in this subset
        for j in range(n):
            if mask & (1 << j):
                product *= arr[j]
                bitCount += 1

                # If product exceeds m, break early
                if product > m:
                    break

        # If product exceeds m, skip this subset
        if product > m:
            continue

        count = m // product

        # Inclusion-Exclusion:
        # - If number of selected primes is odd, add the count
        # - If even, subtract the count
        if bitCount % 2 == 1:
            odd += count
        else:
            even += count

    # Final result based on Inclusion-Exclusion Principle
    return odd - even

    
if __name__ == "__main__":
    arr = [2, 3, 5]
    m = 10
    print(countDivisible(arr, m))  
C#
using System;

class GfG {
    public int countDivisible(int[] arr, int m) {
        int n = arr.Length;
        int odd = 0, even = 0;

        // Total subsets = 2^n (including empty set)
        int powerSet = 1 << n;

        // Iterate through all non-empty subsets of primes
        for (int mask = 1; mask < powerSet; mask++)
        {
            int product = 1;
            
            // Count how many primes are selected
            int bitCount = 0; 

            // Compute the product of selected primes in this subset
            for (int j = 0; j < n; j++)
            {
                if ((mask & (1 << j)) != 0)
                {
                    product *= arr[j];
                    bitCount++;

                    // If product exceeds m, break early
                    if (product > m)
                        break;
                }
            }

            // If product exceeds m, skip this subset
            if (product > m)
                continue;

            int count = m / (int)product;

            // Inclusion-Exclusion:
            // - If number of selected primes is odd, add the count
            // - If even, subtract the count
            if (bitCount % 2 == 1)
                odd += count;
            else
                even += count;
        }

        // Final result based on Inclusion-Exclusion Principle
        return odd - even;
    }

    static void Main() {
        GfG solver = new GfG();
        int[] arr = { 2, 3, 5 };
        int m = 10;

        Console.WriteLine(solver.countDivisible(arr, m));
    }
}
JavaScript
function countDivisible(arr, m) {
    const n = arr.length;
    let odd = 0, even = 0;

    // Total number of subsets = 2^n
    const powerSet = 1 << n;

    // Loop over all non-empty subsets
    for (let mask = 1; mask < powerSet; mask++) {
        let product = 1;
        let valid = true;

        for (let j = 0; j < n; j++) {
            if (mask & (1 << j)) {
                product *= arr[j];
                if (product > m) {
                    valid = false;
                    break;
                }
            }
        }

        if (!valid) continue;

        const count = Math.floor(m / product);

        // Inclusion-Exclusion Principle:
        // Add count if number of set bits is odd, subtract if even
        const bits = countSetBits(mask);
        if (bits % 2 === 1) {
            odd += count;
        } else {
            even += count;
        }
    }

    return odd - even;
}


// Helper function to count set bits (1s) in binary representation.
 
function countSetBits(num) {
    let count = 0;
    while (num > 0) {
        count += num & 1;
        num >>= 1;
    }
    return count;
}

// Driver Code
const primes = [2, 3, 5];
const m = 10;
console.log(countDivisible(primes, m));  

Output
8

Time Complexity: O(n * 2n), Iterates over all non-empty subsets of the n primes (total: 2ⁿ – 1), multiplying the primes in each subset.
Space Complexity: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads