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 total set bits in all numbers from 1 to n | Set 2
Next article icon

Count integers in an Array which are multiples their bits counts

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N elements, the task is to count all the elements which are a multiple of their set bits count.
Examples: 

Input : arr[] = { 1, 2, 3, 4, 5, 6 } Output : 4 Explanation : There numbers which are multiple of their setbits count are { 1, 2, 4, 6 }.  Input : arr[] = {10, 20, 30, 40} Output : 3 Explanation : There numbers which are multiple of their setbits count are { 10, 20, 40 }

Approach: Loop through each array elements one by one. Count the set bits of every number in the array. Check if the current integer is a multiple of its set bits count or not. If 'yes' then increment the counter by 1, else skip that integer. Below is the implementation of above approach: 

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the count of numbers // which are multiple of its set bits count int find_count(vector<int>& arr) {     // variable to store count     int ans = 0;      // iterate over elements of array     for (int i : arr) {          // Get the set-bits count of each element         int x = __builtin_popcount(i);          // Check if the setbits count         // divides the integer i         if (i % x == 0)              // Increment the count             // of required numbers by 1             ans += 1;     }      return ans; }  // Driver code int main() {     vector<int> arr         = { 1, 2, 3, 4, 5, 6 };      cout << find_count(arr);      return 0; } 
Java
class GFG{   // Function to find the count of numbers // which are multiple of its set bits count static int find_count(int []arr) {     // variable to store count     int ans = 0;       // iterate over elements of array     for (int i : arr) {           // Get the set-bits count of each element         int x = Integer.bitCount(i);           // Check if the setbits count         // divides the integer i         if (i % x == 0)               // Increment the count             // of required numbers by 1             ans += 1;     }       return ans; }   // Driver code public static void main(String[] args) {     int []arr         = { 1, 2, 3, 4, 5, 6 };       System.out.print(find_count(arr));   } }  // This code contributed by Princi Singh 
Python3
# Python3 implementation of above approach  # function to return set bits count def bitsoncount(x):     return bin(x).count('1')  # Function to find the count of numbers  # which are multiple of its set bits count  def find_count(arr) :     # variable to store count      ans = 0       # iterate over elements of array      for i in arr :          # Get the set-bits count of each element          x = bitsoncount(i)          # Check if the setbits count          # divides the integer i          if (i % x == 0):              # Increment the count              # of required numbers by 1              ans += 1      return ans  # Driver code  arr = [ 1, 2, 3, 4, 5, 6 ]  print(find_count(arr))  # This code is contributed by Sanjit_Prasad 
C#
using System;  public class GFG{    // Function to find the count of numbers // which are multiple of its set bits count static int find_count(int []arr) {     // Variable to store count     int ans = 0;        // Iterate over elements of array     foreach (int i in arr) {            // Get the set-bits count of each element         int x = bitCount(i);            // Check if the setbits count         // divides the integer i         if (i % x == 0)                // Increment the count             // of required numbers by 1             ans += 1;     }        return ans; } static int bitCount(long x) {     int setBits = 0;     while (x != 0) {         x = x & (x - 1);         setBits++;     }     return setBits; }    // Driver code public static void Main(String[] args) {     int []arr         = { 1, 2, 3, 4, 5, 6 };        Console.Write(find_count(arr));    } } // This code contributed by Princi Singh 
JavaScript
<script>   // Function to find the count of numbers // which are multiple of its set bits count function find_count(arr) {     // Variable to store count     var ans = 0;        // Iterate over elements of array     for (var i=0;i<=arr.length;i++) {            // Get the set-bits count of each element         var x = bitCount(i);            // Check if the setbits count         // divides the integer i         if (i % x == 0)                // Increment the count             // of required numbers by 1             ans += 1;     }        return ans; } function bitCount( x) {     var setBits = 0;     while (x != 0) {         x = x & (x - 1);         setBits++;     }     return setBits; } var arr = [ 1, 2, 3, 4, 5, 6 ];   document.write(find_count(arr));      // This code contributed by SoumikMondal </script> 

Output
4


Time complexity:- O(nlog(max(arr[])), where n is the size of the array, 
Space complexity:- O(1)

Approach 2:

Another approach would be to precompute the set bits count of all integers up to a certain limit (e.g., the maximum value in the array), and store them in an array or a hash table. Then, we can loop through the array and look up the set bits count of each element in the table, and check if it divides the element. This approach can be faster if we have to process multiple arrays with the same set of integers.

Here's an example implementation of the second approach:

C++
#include <bits/stdc++.h> using namespace std;  const int MAX_N = 1000000;  // Precomputed set bits count int set_bits_count[MAX_N + 1];  void precompute_set_bits_count() {     for (int i = 1; i <= MAX_N; i++) {         set_bits_count[i] = set_bits_count[i >> 1] + (i & 1);     } }  // Function to find the count of numbers // which are multiple of its set bits count int find_count(vector<int>& arr) {     // variable to store count     int ans = 0;      // iterate over elements of array     for (int i : arr) {          // Get the set-bits count of each element         int x = set_bits_count[i];          // Check if the setbits count         // divides the integer i         if (i % x == 0)              // Increment the count             // of required numbers by 1             ans += 1;     }      return ans; }  // Driver code int main() {     precompute_set_bits_count();      vector<int> arr         = { 1, 2, 3, 4, 5, 6 };      cout << find_count(arr);      return 0; } 
Java
import java.util.*;  public class Main {      static final int MAX_N = 1000000;      // Precomputed set bits count     static int[] set_bits_count = new int[MAX_N + 1];      static void precompute_set_bits_count() {         for (int i = 1; i <= MAX_N; i++) {             set_bits_count[i] = set_bits_count[i >> 1] + (i & 1);         }     }      // Function to find the count of numbers     // which are multiple of its set bits count     static int find_count(ArrayList<Integer> arr) {         // variable to store count         int ans = 0;          // iterate over elements of array         for (int i : arr) {              // Get the set-bits count of each element             int x = set_bits_count[i];              // Check if the setbits count             // divides the integer i             if (i % x == 0)                  // Increment the count                 // of required numbers by 1                 ans += 1;         }          return ans;     }      // Driver code     public static void main(String[] args) {         precompute_set_bits_count();          ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));          System.out.println(find_count(arr));     } } 
Python3
MAX_N = 1000000  # Precomputed set bits count set_bits_count = [0] * (MAX_N + 1)  def precompute_set_bits_count():     for i in range(1, MAX_N + 1):         set_bits_count[i] = set_bits_count[i >> 1] + (i & 1)  # Function to find the count of numbers # which are multiple of its set bits count def find_count(arr):     # variable to store count     ans = 0      # iterate over elements of array     for i in arr:          # Get the set-bits count of each element         x = set_bits_count[i]          # Check if the setbits count         # divides the integer i         if i % x == 0:              # Increment the count             # of required numbers by 1             ans += 1      return ans  # Driver code if __name__ == '__main__':     precompute_set_bits_count()      arr = [1, 2, 3, 4, 5, 6]      print(find_count(arr)) 
C#
using System; using System.Collections.Generic;  public class MainClass { const int MAX_N = 1000000;   // Precomputed set bits count static int[] set_bits_count = new int[MAX_N + 1];  static void precompute_set_bits_count() {     for (int i = 1; i <= MAX_N; i++)     {         set_bits_count[i] = set_bits_count[i >> 1] + (i & 1);     } }  // Function to find the count of numbers // which are multiple of its set bits count static int find_count(List<int> arr) {     // variable to store count     int ans = 0;      // iterate over elements of array     foreach (int i in arr)     {          // Get the set-bits count of each element         int x = set_bits_count[i];          // Check if the setbits count         // divides the integer i         if (i % x == 0)              // Increment the count             // of required numbers by 1             ans += 1;     }      return ans; }  // Driver code public static void Main() {     precompute_set_bits_count();      List<int> arr = new List<int>() { 1, 2, 3, 4, 5, 6 };      Console.WriteLine(find_count(arr)); } } 
JavaScript
const MAX_N = 1000000;  // Precomputed set bits count const set_bits_count = new Array(MAX_N + 1).fill(0);  function precompute_set_bits_count() {     for (let i = 1; i <= MAX_N; i++) {         set_bits_count[i] = set_bits_count[i >> 1] + (i & 1);     } }  // Function to find the count of numbers // which are multiple of its set bits count function find_count(arr) {     // variable to store count     let ans = 0;      // iterate over elements of array     for (let i of arr) {         // Get the set-bits count of each element         let x = set_bits_count[i];          // Check if the setbits count         // divides the integer i         if (i % x == 0) {              // Increment the count             // of required numbers by 1             ans += 1;         }     }      return ans; }  // Driver code if (require.main === module) {     precompute_set_bits_count();      const arr = [1, 2, 3, 4, 5, 6];      console.log(find_count(arr)); }  // Contributed by sdeadityasharma 

Output
4

Time complexity:- O(nlog(max(arr[])), where n is the size of the array, 
Auxiliary Space:- O(N)
 


Next Article
Count total set bits in all numbers from 1 to n | Set 2

S

Sanjit_Prasad
Improve
Article Tags :
  • Bit Magic
  • C++ Programs
  • DSA
  • Arrays
  • setBitCount
Practice Tags :
  • Arrays
  • Bit Magic

Similar Reads

  • How to Count Set Bits in an Integer in C++?
    In binary representation of a number, a set bit is defined as the binary digit (bit) that is set to 1. In this article, we will learn how to count the set bits in a given integer in C++. Example Input: 13Output:The number of set bits in 13 (1101) is: 3Counting Set Bits in an IntegerTo count the set
    2 min read
  • Count the number of 1's and 0's in a binary array using STL in C++ ?
    Given a binary array, the task is to count the number of 1's and 0's in this array using STL in C++. Examples: Input: arr[] = {1, 0, 0, 1, 0, 0, 1} Output: 1's = 3, 0's = 4 Input: arr[] = {1, 1, 1, 1, 0, 0, 1} Output: 1's = 5, 0's = 2 Approach: We can count the same using count_if() function present
    1 min read
  • Count pairs whose Bitwise AND exceeds Bitwise XOR from a given array
    Given an array arr[] of size N, the task is to count the number of pairs from the given array such that the Bitwise AND (&) of each pair is greater than its Bitwise XOR(^). Examples : Input: arr[] = {1, 2, 3, 4} Output:1Explanation:Pairs that satisfy the given conditions are: (2 & 3) > (2
    6 min read
  • How to Count the Number of Occurrences of a Value in an Array in C++?
    In C++, an array is a data structure that stores the collection of the same type of data in a contiguous memory location. In this article, we will learn how to count the number of occurrences of a value in an array in C++. Example: Input: arr= {2, 4, 5 ,2 ,4 , 5, 2 , 3 ,8}Target = 2Output: Number of
    2 min read
  • Count total set bits in all numbers from 1 to n | Set 2
    Given a positive integer N, the task is to count the sum of the number of set bits in the binary representation of all the numbers from 1 to N.Examples: Input: N = 3 Output: 4 DecimalBinarySet Bit Count101121013112 1 + 1 + 2 = 4Input: N = 16 Output: 33 Recommended PracticeCount total set bitsTry It!
    11 min read
  • Count total set bits in all numbers from 1 to N | Set 3
    Given a positive integer N, the task is to count the total number of set bits in binary representation of all the numbers from 1 to N. Examples: Input: N = 3 Output: 4 setBits(1) + setBits(2) + setBits(3) = 1 + 1 + 2 = 4 Input: N = 6 Output: 9 Approach: Solution to this problem has been published in
    12 min read
  • Count of Arrays of size N with elements in range [0, (2^K)-1] having maximum sum & bitwise AND 0
    Given two integers N and K, The task is to find the count of all possible arrays of size N with maximum sum & bitwise AND of all elements as 0. Also, elements should be within the range of 0 to 2K-1. Examples: Input: N = 3, K = 2Output: 9Explanation: 22 - 1 = 3, so elements of arrays should be b
    6 min read
  • Bitwise OR of all unordered pairs from a given array
    Given an array arr[] of size N, the task is to find the Bitwise XOR of all possible unordered pairs from the given array. Examples: Input: arr[] = {1, 5, 3, 7} Output: 7 Explanation: All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7) Bitwise OR of all possible pairs are
    8 min read
  • Count of even set bits between XOR of two arrays
    Given two arrays A[] and B[] having N and M positive elements respectively. The task is to count the number of elements in array A with even number of set bits in XOR for every element of array B. Examples: Input: A[] = { 4, 2, 15, 9, 8, 8 }, B[] = { 3, 4, 22 } Output: 2 4 4 Explanation: Binary repr
    11 min read
  • bitset count() in C++ STL
    bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. Syntax: int count() Parameter: The function accepts no parameter. Return Value: The function returns the number of set bits. It returns the total number of ones or the number of se
    2 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