Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count array elements whose count of divisors is a prime number
Next article icon

Count array elements having exactly K divisors

Last Updated : 13 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers and an integer K, the task is to count the number of array elements having exactly K divisors.

Examples:

Input: N = 5, arr[] = { 3, 6, 2, 9, 4 }, K = 2
Output: 2
Explanation: arr[0] (= 3) and arr[2] (= 2) have exactly 2 divisors.

Input: N = 5, arr[] = { 3, 6, 2, 9, 4 }, K = 3
Output: 2
Explanation: arr[3] (= 9) and arr[4] (= 4) have exactly 3 divisors

Approach: The idea to solve this problem is to compute the total number of divisors of each array element and store them in a Map. Then, traverse the array and for every array element, check if has exactly K divisors. Print the count of such numbers. Follow the steps below to solve the problem:

  • Find the maximum element present in the array.
  • Initialize an array prime[].
  • Store all primes present in the range [2, maximum element in the array] in the array prime[] using Sieve of Eratosthenes.
  • Traverse the array and prime factorize each array element using the given formula:

where ai are prime factors and pi are integral powers to which they are raised.

  • Count the total number of the divisors of each array element using the following formula:
  • Initialize a Map to store the total number of divisors of each array element.
  • Traverse the array and initialize a variable, say, count, to count the number of elements having exactly K total number of divisors.
  • Print the number of elements having exactly K divisors.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Stores prime numbers // using Sieve of Eratosthenes bool prime[100000];  // Function to find the maximum element int maximumElement(int arr[], int N) {   // Stores the maximum element   // of the array   int max = arr[0];    // Traverse the array   for (int i = 0; i < N; i++) {      // If current element     // is maximum so far     if (max < arr[i]) {        // Update maximum       max = arr[i];     }   }    // Return maximum element   return max; }  // Function to find the prime numbers // using sieve of eratosthenes algorithm void sieveOfEratosthenes(int max) {   // Calculate primes using Sieve   memset(prime, true, max+1);    for (int p = 2; p * p < max; p++)      // If current element is prime     if (prime[p] == true)        // Make all multiples non-prime       for (int i = p * 2; i < max; i += p)         prime[i] = false; }  // Function to count divisors of n int divCount(int n) {    // Traversing through   // all prime numbers   int total = 1;   for (int p = 2; p <= n; p++) {      // If it is a prime number     if (prime[p]) {        // Calculate number of divisors       // with the formula       // number of divisors = (p1 + 1) * (p2 + 1)       // *.....* (pn + 1)       // n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)       // ai: prime divisor of n       // pi: power in factorization       int count = 0;        if (n % p == 0) {          while (n % p == 0) {           n = n / p;           count++;         }         total = total * (count + 1);       }     }   }    // Return the total number of divisors   return total; }  // Function to count array elements // having exactly K divisors int countElements(int arr[], int N, int K) {    // Initialize a map to store   // count of divisors of array elements   map<int, int> map;    // Traverse the array   for (int i = 0; i < N; i++) {      // If element is not already present in     // the Map, then insert it into the Map     if (map.find(arr[i]) == map.end()) {       // Function call to count the total       // number of divisors       map.insert({arr[i], divCount(arr[i])});     }   }    // Stores the number of   // elements with divisor K   int count = 0;    // Traverse the array   for (int i = 0; i < N; i++) {      // If current element     // has exactly K divisors     if (map.at(arr[i]) == K) {       count++;     }   }    // Return the number of   // elements having K divisors   return count; }  // Driver Code int main() {    int arr[] = { 3, 6, 2, 9, 4 };   int N = sizeof(arr) / sizeof(arr[0]);   int K = 2;    // Find the maximum element   int max = maximumElement(arr, N);    // Generate all prime numbers   sieveOfEratosthenes(max);    cout << countElements(arr, N, K);    return 0; }  // This code is contributed by Dharanendra L V 
Java
// Java program for the above approach import java.util.*; class GFG {      // Stores prime numbers     // using Sieve of Eratosthenes     public static boolean prime[];      // Function to find the maximum element     public static int maximumElement(         int arr[], int N)     {         // Stores the maximum element         // of the array         int max = arr[0];          // Traverse the array         for (int i = 0; i < N; i++) {              // If current element             // is maximum so far             if (max < arr[i]) {                  // Update maximum                 max = arr[i];             }         }          // Return maximum element         return max;     }      // Function to find the prime numbers     // using sieve of eratosthenes algorithm     public static void sieveOfEratosthenes(int max)     {         // Initialize primes having         // size of maximum element + 1         prime = new boolean[max + 1];          // Calculate primes using Sieve         Arrays.fill(prime, true);          for (int p = 2; p * p < max; p++)              // If current element is prime             if (prime[p] == true)                  // Make all multiples non-prime                 for (int i = p * 2; i < max; i += p)                     prime[i] = false;     }      // Function to count divisors of n     public static int divCount(int n)     {          // Traversing through         // all prime numbers         int total = 1;         for (int p = 2; p <= n; p++) {              // If it is a prime number             if (prime[p]) {                  // Calculate number of divisors                 // with the formula                 // number of divisors = (p1 + 1) * (p2 + 1)                 // *.....* (pn + 1)                 // n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)                 // ai: prime divisor of n                 // pi: power in factorization                 int count = 0;                  if (n % p == 0) {                      while (n % p == 0) {                         n = n / p;                         count++;                     }                     total = total * (count + 1);                 }             }         }          // Return the total number of divisors         return total;     }      // Function to count array elements     // having exactly K divisors     public static int countElements(         int arr[], int N, int K)     {          // Initialize a map to store         // count of divisors of array elements         Map<Integer, Integer> map             = new HashMap<Integer, Integer>();          // Traverse the array         for (int i = 0; i < N; i++) {              // If element is not already present in             // the Map, then insert it into the Map             if (!map.containsKey(arr[i])) {                 // Function call to count the total                 // number of divisors                 map.put(arr[i], divCount(arr[i]));             }         }          // Stores the number of         // elements with divisor K         int count = 0;          // Traverse the array         for (int i = 0; i < N; i++) {              // If current element             // has exactly K divisors             if (map.get(arr[i]) == K) {                 count++;             }         }          // Return the number of         // elements having K divisors         return count;     }      // Driver Code     public static void main(         String[] args)     {         int arr[] = { 3, 6, 2, 9, 4 };         int N = arr.length;         int K= 2;          // Find the maximum element         int max = maximumElement(arr, N);          // Generate all prime numbers         sieveOfEratosthenes(max);          System.out.println(countElements(arr, N, K));     } } 
Python3
# Python3 program for the above approach  # Stores prime numbers # using Sieve of Eratosthenes  # Function to find the maximum element def maximumElement(arr, N):        # Stores the maximum element     # of the array     max = arr[0]      # Traverse the array     for i in range(N):          # If current element         # is maximum so far         if (max < arr[i]):              # Update maximum             max = arr[i]      # Return maximum element     return max  # Function to find the prime numbers # using sieve of eratosthenes algorithm def sieveOfEratosthenes(max):     global prime     for p in range(2, max + 1):         if p * p > max:             break          # If current element is prime         if (prime[p] == True):              # Make all multiples non-prime             for i in range(2 * p, max, p):                 prime[i] = False     return prime  # Function to count divisors of n def divCount(n):      # Traversing through     # all prime numbers     total = 1     for p in range(2, n + 1):          # If it is a prime number         if (prime[p]):              # Calculate number of divisors             # with the formula             # number of divisors = (p1 + 1) * (p2 + 1)             # *.....* (pn + 1)             # n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)             # ai: prime divisor of n             # pi: power in factorization             count = 0              if (n % p == 0):                 while (n % p == 0):                     n = n // p                     count += 1                 total = total * (count + 1)      # Return the total number of divisors     return total  # Function to count array elements # having exactly K divisors def countElements(arr, N, K):      # Initialize a map to store     # count of divisors of array elements     mp = {}      # Traverse the array     for i in range(N):          # If element is not already present in         # the Map, then insert it into the Map         if (arr[i] not in mp):                          # Function call to count the total             # number of divisors             mp[arr[i]] = divCount(arr[i])      # Stores the number of     # elements with divisor K     count = 0      # Traverse the array     for i in range(N):          # If current element         # has exactly K divisors         if (mp[arr[i]] == K):             count += 1      # Return the number of     # elements having K divisors     return count  # Driver Code if __name__ == '__main__':     prime = [True for i in range(10**6)]     arr = [3, 6, 2, 9, 4]     N = len(arr)     K= 2      # Find the maximum element     max = maximumElement(arr, N)      # Generate all prime numbers     prime = sieveOfEratosthenes(max)     print(countElements(arr, N, K))  # This code is contributed by mohit kumar 29 
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG {      // Stores prime numbers     // using Sieve of Eratosthenes     public static bool []prime;      // Function to find the maximum element     public static int maximumElement(         int []arr, int N)     {                // Stores the maximum element         // of the array         int max = arr[0];          // Traverse the array         for (int i = 0; i < N; i++)         {              // If current element             // is maximum so far             if (max < arr[i])             {                  // Update maximum                 max = arr[i];             }         }          // Return maximum element         return max;     }      // Function to find the prime numbers     // using sieve of eratosthenes algorithm     public static void sieveOfEratosthenes(int max)     {                // Initialize primes having         // size of maximum element + 1         prime = new bool[max + 1];          // Calculate primes using Sieve         for (int i = 0; i < prime.Length; i++)         prime[i] = true;         for (int p = 2; p * p < max; p++)              // If current element is prime             if (prime[p] == true)                  // Make all multiples non-prime                 for (int i = p * 2; i < max; i += p)                     prime[i] = false;     }      // Function to count divisors of n     public static int divCount(int n)     {          // Traversing through         // all prime numbers         int total = 1;         for (int p = 2; p <= n; p++)         {              // If it is a prime number             if (prime[p])             {                  // Calculate number of divisors                 // with the formula                 // number of divisors = (p1 + 1) * (p2 + 1)                 // *.....* (pn + 1)                 // n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)                 // ai: prime divisor of n                 // pi: power in factorization                 int count = 0;                 if (n % p == 0)                  {                     while (n % p == 0)                      {                         n = n / p;                         count++;                     }                     total = total * (count + 1);                 }             }         }          // Return the total number of divisors         return total;     }      // Function to count array elements     // having exactly K divisors     public static int countElements(int []arr,                                      int N, int K)     {          // Initialize a map to store         // count of divisors of array elements         Dictionary<int, int> map             = new Dictionary<int, int>();          // Traverse the array         for (int i = 0; i < N; i++)         {              // If element is not already present in             // the Map, then insert it into the Map             if (!map.ContainsKey(arr[i]))              {                                // Function call to count the total                 // number of divisors                 map.Add(arr[i], divCount(arr[i]));             }         }          // Stores the number of         // elements with divisor K         int count = 0;          // Traverse the array         for (int i = 0; i < N; i++)          {              // If current element             // has exactly K divisors             if (map[arr[i]] == K)              {                 count++;             }         }          // Return the number of         // elements having K divisors         return count;     }      // Driver Code     public static void Main(String[] args)     {         int []arr = {3, 6, 2, 9, 4};         int N = arr.Length;         int K= 2;          // Find the maximum element         int max = maximumElement(arr, N);          // Generate all prime numbers         sieveOfEratosthenes(max);         Console.WriteLine(countElements(arr, N, K));     } }  // This code is contributed by 29AjayKumar  
JavaScript
<script>  // Javascript program for the above approach  // Stores prime numbers // using Sieve of Eratosthenes let prime = new Array(100000);  // Function to find the maximum element function maximumElement(arr, N) { // Stores the maximum element // of the array let max = arr[0];  // Traverse the array for (let i = 0; i < N; i++) {      // If current element     // is maximum so far     if (max < arr[i]) {      // Update maximum     max = arr[i];     } }  // Return maximum element return max; }  // Function to find the prime numbers // using sieve of eratosthenes algorithm function sieveOfEratosthenes(max) { // Calculate primes using Sieve prime.fill(true, 0, max + 1)  for (let p = 2; p * p < max; p++)      // If current element is prime     if (prime[p] == true)      // Make all multiples non-prime     for (let i = p * 2; i < max; i += p)         prime[i] = false; }  // Function to count divisors of n function divCount(n) {  // Traversing through // all prime numbers let total = 1; for (let p = 2; p <= n; p++) {      // If it is a prime number     if (prime[p]) {      // Calculate number of divisors     // with the formula     // number of divisors = (p1 + 1) * (p2 + 1)     // *.....* (pn + 1)     // n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)     // ai: prime divisor of n     // pi: power in factorization     let count = 0;      if (n % p == 0) {          while (n % p == 0) {         n = n / p;         count++;         }         total = total * (count + 1);     }     } }  // Return the total number of divisors return total; }  // Function to count array elements // having exactly K divisors function countElements(arr, N, K) {  // Initialize a map to store // count of divisors of array elements let map = new Map();  // Traverse the array for (let i = 0; i < N; i++) {      // If element is not already present in     // the Map, then insert it into the Map     if (!map.has(arr[i])) {     // Function call to count the total     // number of divisors     map.set(arr[i], divCount(arr[i]));     } }  // Stores the number of // elements with divisor K let count = 0;  // Traverse the array for (let i = 0; i < N; i++) {      // If current element     // has exactly K divisors     if (map.get(arr[i]) == K) {     count++;     } }  // Return the number of // elements having K divisors return count; }  // Driver Code  let arr = [ 3, 6, 2, 9, 4 ]; let N = arr.length; let K = 2;  // Find the maximum element let max = maximumElement(arr, N);  // Generate all prime numbers sieveOfEratosthenes(max);  document.write(countElements(arr, N, K));  // This code is contributed by _saurabh_jaiswal  </script> 

Output: 
2

 

Time Complexity: O(N + maxlog(log(max) + log(max)), where max is the maximum array element.
Auxiliary Space: O(max), where max is the maximum array element.


Next Article
Count array elements whose count of divisors is a prime number

D

deepika_sharma
Improve
Article Tags :
  • Misc
  • Searching
  • Mathematical
  • DSA
  • Arrays
  • sieve
  • prime-factor
  • Prime Number
  • divisors
Practice Tags :
  • Arrays
  • Mathematical
  • Misc
  • Prime Number
  • Searching
  • sieve

Similar Reads

  • Count array elements having sum of digits equal to K
    Given an array arr[] of size N, the task is to count the number of array elements whose sum of digits is equal to K. Examples: Input: arr[] = {23, 54, 87, 29, 92, 62}, K = 11Output: 2Explanation: 29 = 2 + 9 = 1192 = 9 + 2 = 11 Input: arr[]= {11, 04, 57, 99, 98, 32}, K = 18Output: 1 Approach: Follow
    6 min read
  • Count numbers up to N having exactly 5 divisors
    Given a positive integer N, the task is to count the number of integers from the range [1, N] having exactly 5 divisors. Examples: Input: N = 18Output: 1Explanation:From all the integers over the range [1, 18], 16 is the only integer that has exactly 5 divisors, i.e. 1, 2, 8, 4 and 16.Therefore, the
    15+ min read
  • Count divisors of array multiplication
    Given an array with N elements, the task is to find the count of factors of a number X, which is the product of all array elements. Examples: Input : 5 5 Output : 3 5 * 5 = 25, the factors of 25 are 1, 5, 25 whose count is 3 Input : 3 5 7 Output : 8 3 * 5 * 7 = 105, the factors of 105 are 1, 3, 5, 7
    13 min read
  • Count array elements whose count of divisors is a prime number
    Given an array arr[] consisting of N positive integers, the task is to find the number of array elements whose count of divisors is a prime number. Examples: Input: arr[] = {3, 6, 4}Output: 2Explanation:The count of divisors for each element are: arr[0]( = 3): 3 has 2 divisors i.e., 1 and 3.arr[1](
    9 min read
  • Count frequency of digit K in given Array
    Given an array arr[] of integers of size N and a single digit integer K. The task is to find the total count of occurrences of the digit K in the array Examples: Input: arr[] = {15, 66, 26, 91}, K = 6Output: 3Explanation: Occurrences of 6 in each array elements are: 0, 2, 1, 0 respectively.Therefore
    5 min read
  • Count Subarrays With Exactly K Distinct Elements
    Given an array arr[] and an integer k, the task is to find the count of subarrays such that each subarray has exactly k distinct elements. Examples: Input: arr[] = [1, 2, 2, 3], k = 2 Output: 4 Explanation: Subarrays with exactly 2 distinct elements are: [1, 2], [1, 2, 2] and [2, 3]. Input: arr[] =
    10 min read
  • Count the divisors or multiples present in the Array for each element
    Given an array A[] with N integers, for each integer A[i] in the array, the task is to find the number of integers A[j] (j != i) in the array such that A[i] % A[j] = 0 or A[j] % A[i] = 0. Examples: Input: A = {2, 3, 4, 5, 6}Output: 2 1 1 0 2Explanation: For i=0, the valid indices are 2 and 4 as 4%2
    8 min read
  • Count array elements whose all distinct digits appear in K
    Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the count of array elements whose distinct digits are a subset of the digits of K. Examples: Input: arr[] = { 1, 12, 1222, 13, 2 }, K = 12Output: 4Explanation: Distinct Digits of K are { 1, 2 } Disti
    15+ min read
  • Count subarrays made up of elements having exactly K set bits
    Given an array arr[] consisting of N integers and an integer K, the task is to count the number of subarrays possible consisting of elements having exactly K set bits. Examples: Input: arr[] = {4, 2, 1, 5, 6}, K = 2Output: 3Explanation: The subarrays made up of elements having exactly 2 set bits are
    7 min read
  • Count Pairs with equal elements and Divisible Index Sum
    Given an array arr[] of length N and an integer k. You have to return the count of all the pairs (i, j) such that: arr[i] == arr[j]i<j(i+j) is divisible by kExamples: Input: N = 5, k = 3, arr[] = {1, 2, 3, 2, 1}Output: 2Explanation: arr[2] = arr[4] and 2<4 , (2+4) = 6 is divisible by 3.arr[1]
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences