Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Puzzles
  • Funny Riddles
  • Interesting Riddles
  • Mathematical Riddles
  • Animal Riddles
  • Mathematical Puzzles
  • Rubik's Cube
  • Aptitude-Puzzles
  • Top 100 Puzzles
  • Puzzles Quiz
Open In App
Next Article:
Count of 1's after flipping the bits at multiples from 1 to N
Next article icon

Count of 1's after flipping the bits at multiples from 1 to N

Last Updated : 16 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given N sized binary array A[] containing all 0's initially. The task is to find the final count of 1's after flipping the bits at multiples from 1 to N.

Examples:

Input: A[] = [0, 0, 0, 0]
Output: 2
Explanation: 
Flipping bits at multiples of 1 - [1, 1, 1, 1]
Flipping bits at multiples of 2 - [1, 0, 1, 0]
Flipping bits at multiples of 3 - [1, 0, 0, 0]
Flipping bits at multiples of 4 - [1, 0, 0, 1] 
Therefore count of 1's after final flipping is 2.        

Input: A[] = [0, 0, 0, 0, 0, 0, 0]
Output: 2
Explanation:
Flipping bits at multiples of 1 - [1, 1, 1, 1, 1, 1, 1]
Flipping bits at multiples of 2 - [1, 0, 1, 0, 1, 0, 1]
Flipping bits at multiples of 3 - [1, 0, 0, 0, 1, 1, 1]
Flipping bits at multiples of 4 - [1, 0, 0, 1, 1, 1, 1]
Flipping bits at multiples of 5 - [1, 0, 0, 1, 0, 1, 1]
Flipping bits at multiples of 6 - [1, 0, 0, 1, 0, 0, 1]
Flipping bits at multiples of 7 - [1, 0, 0, 1, 0, 0, 0]
Therefore count of 1's after final flipping is 2

Naive Approach: The basic idea of the solution is based on greedy approach. 

For each element from 1 to N, flip all the elements at its multiples. The final count of 1 in the array is the answer.

Follow the steps below to implement the approach:

  • Create an array of size N and fill it with 0.
  • Run a loop i = 1 to i = N, and for each i,
    • run a loop j = i - 1 to N with increment = i.
      • Flip the bits at each j.
  • Iterate over the array and calculate number of 1.

Implementation of the above discussed approach is given below.

C++
// C++ code to implement the approach #include <iostream> using namespace std;  // Function to calculate number of 1 // in the final array int findOnes(int N, int arr[]) {     int count = 0;      // Loop to flip the elements      // at multiples of i     for (int i = 1; i <= N; i++) {         for (int j = i - 1; j < N; j += i) {             if (arr[j] == 0)                 arr[j] = 1;             else                 arr[j] = 0;         }     }      // Loop to determine 1s at final array     for (int i = 0; i < N; i++) {         if (arr[i] == 1)             count++;     }      return count; }  // Driver Code int main() {     int N = 4;     int arr[N];      for (int i = 0; i < N; i++)         arr[i] = 0;      int count = findOnes(N, arr);     cout << count;      return 0; } 
Java
// Java code to implement the approach import java.io.*;  class GFG {    // Function to calculate number of 1   // in the final array   static int findOnes(int N, int arr[])   {     int count = 0;      // Loop to flip the elements      // at multiples of i     for (int i = 1; i <= N; i++) {       for (int j = i - 1; j < N; j += i) {         if (arr[j] == 0)           arr[j] = 1;         else           arr[j] = 0;       }     }      // Loop to determine 1s at final array     for (int i = 0; i < N; i++) {       if (arr[i] == 1)         count++;     }      return count;   }    // Driver Code   public static void main (String[] args) {     int N = 4;     int[] arr = new int[N];      for (int i = 0; i < N; i++)       arr[i] = 0;      int count = findOnes(N, arr);     System.out.println(count);   } }  // This code is contributed by hrithikgarg03188. 
Python3
# Python code to implement the approach  # Function to calculate number of 1 # in the final array def findOnes(N, arr):     count = 0      # Loop to flip the elements      # at multiples of i     for i in range(1, N + 1):         for j in range(i - 1, N, i):             if (arr[j] == 0):                 arr[j] = 1             else:                 arr[j] = 0      # Loop to determine 1s at final array     for i in range(N):         if (arr[i] == 1):             count += 1      return count  # Driver Code N = 4 arr = [0]*N  for i in range(N):     arr[i] = 0  count = findOnes(N, arr) print(count)  # This code is contributed by shinjanpatra 
C#
// C# code to implement the approach using System;  class GFG {    // Function to calculate number of 1   // in the final array   static int findOnes(int N, int[] arr)   {     int count = 0;      // Loop to flip the elements     // at multiples of i     for (int i = 1; i <= N; i++) {       for (int j = i - 1; j < N; j += i) {         if (arr[j] == 0)           arr[j] = 1;         else           arr[j] = 0;       }     }      // Loop to determine 1s at final array     for (int i = 0; i < N; i++) {       if (arr[i] == 1)         count++;     }      return count;   }    // Driver Code   public static void Main()   {     int N = 4;     int[] arr = new int[N];      for (int i = 0; i < N; i++)       arr[i] = 0;      int count = findOnes(N, arr);     Console.WriteLine(count);   } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
<script>  // JavaScript code to implement the approach  // Function to calculate number of 1 // in the final array function findOnes(N, arr) {     let count = 0;      // Loop to flip the elements      // at multiples of i     for (let i = 1; i <= N; i++) {         for (let j = i - 1; j < N; j += i) {             if (arr[j] == 0)                 arr[j] = 1;             else                 arr[j] = 0;         }     }      // Loop to determine 1s at final array     for (let i = 0; i < N; i++) {         if (arr[i] == 1)             count++;     }      return count; }  // Driver Code  let N = 4; let arr = new Array(N);  for (let i = 0; i < N; i++)     arr[i] = 0;  let count = findOnes(N, arr); document.write(count);  // This code is contributed by shinjanpatra  </script> 

 
 


Output
2

Time Complexity: O(N*log N)
Auxiliary Space: O(N)
 

Efficient Approach: The efficient approach to solve this problem is based on following mathematical observation:
 

After flipping all the bits at multiples of numbers in range 1 to N, there will be only floor(?N) 1s left. 

This relation can be proved as per shown below:

Initially, all the elements are 0. 

Lemma 1: At any index i, the final element will be 1 if it is flipped odd number of times. This is trivial.

Lemma 2: For any index i, the number of times element at that index will be flipped equals number of factors of that coin.
Since we flip elements at multiples of 1, 2, 3, 4, … N. For each factor of any index i, it will be flipped. 

Lemma 3: From Lemma 1 and Lemma 2, all the indices having odd number of factors will have 1 as its final element .
For any natural number N, we can write it in its prime factorization form:

  • N = ?a x ?b x ?c x ?d ….
    where ? < ? < ? < ? …. are prime numbers and a, b, c, d are whole numbers.
  • Then, total number of factors of N = (a+1) x (b+1) x (c+1) x (d+1) x …
  • Hence, we want ((a+1) x (b+1) x (c+1) x (d+1) x …) to be odd.
  • => ((a+1) x (b+1) x (c+1) x (d+1) x …) is odd if (a+1) x (b+1) x (c+1) x (d+1) x … is odd
    => (a+1) x (b+1) x (c+1) x (d+1) x …        is odd if   (a+1), (b+1), (c+1), (d+1) … is odd
    => (a+1), (b+1), (c+1), (d+1)                   is odd if    a, b, c, d, …. is even
  • Hence, N = ?a x ?b x ?c x ?d …. should has a, b, c, d, … as even whole numbers. This is only possible if N is a perfect square.

Therefore, all indices which are perfect squares will have 1 as their final element.

Number of perfect squares below N = ??N? 

Implementation of the above discussed observation is given below.

C++
// C++ code to implement the approach #include <cmath> #include <iostream> using namespace std;  // Function to count number of 1's  // in final array int findOnes(int N, int arr[])  {     return floor(sqrt(N));  }  // Driver Code int main() {     int N = 4;     int arr[] = { 0, 0, 0, 0 };      int count = findOnes(N, arr);     cout << count;      return 0; } 
Java
// JAVA code to implement the approach import java.util.*; class GFG  {    // Function to count number of 1's   // in final array   public static int findOnes(int N, int arr[])   {     return (int)Math.floor((int)Math.sqrt(N));   }    // Driver Code   public static void main(String[] args)   {     int N = 4;     int arr[] = new int[] { 0, 0, 0, 0 };      int count = findOnes(N, arr);     System.out.print(count);   } }  // This code is contributed by Taranpreet 
C#
// C# code to implement the approach using System; class GFG {      // Function to count number of 1's     // in final array     static int findOnes(int N, int[] arr)     {         return (int)(Math.Floor(Math.Sqrt(N)));     }      // Driver Code     public static void Main()     {         int N = 4;         int[] arr = { 0, 0, 0, 0 };          int count = findOnes(N, arr);         Console.Write(count);     } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
<script> // Javascript code to implement the approach  // Function to count number of 1's  // in final array function findOnes(N, arr)  {     return Math.floor(Math.sqrt(N));  }  // Driver Code let N = 4; let arr = [ 0, 0, 0, 0 ];  let count = findOnes(N, arr); document.write(count);  // This code is contributed by Samim Hossain Mondal. </script> 
Python3
# Python code to implement the approach  # Function to count number of 1's  # in final array import math   def findOnes(N, arr):      return math.floor(math.sqrt(N))   # Driver Code N = 4 arr = [ 0, 0, 0, 0 ]  count = findOnes(N, arr) print(count)  # This code is contributed by shinjanpatra 

Output
2

Time Complexity: O(logN) as it is using inbuilt sqrt function
Auxiliary Space: O(1)


Next Article
Count of 1's after flipping the bits at multiples from 1 to N

A

anujanonymous
Improve
Article Tags :
  • Mathematical
  • Puzzles
  • Geeks Premier League
  • DSA
  • Geeks-Premier-League-2022
  • binary-string
Practice Tags :
  • Mathematical
  • Puzzles

Similar Reads

    Number formed by flipping all bits to the left of rightmost set bit
    Given an integer N, the task is to flip all the bits to the left of rightmost set bit and print the number generated. Examples: Input: N = 10 Output: 6 Explanation: 10 (1010 in binary) flipping all bits left to rightmost set bit (index 2) -> 6 (0110 in binary) Input: N = 120 Output: 8 Explanation
    8 min read
    Flip bits of the sum of count of set bits of two given numbers
    Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representatio
    5 min read
    Count number of 1s in the array after N moves
    Given an array of size N in which initially all the elements are 0(zero). The task is to count the number of 1's in the array after performing N moves on the array as explained:In each move (starting from 1 to N) the element at the position of the multiple of the move number is changed from 0 to 1 o
    9 min read
    Flip consecutive set bits starting from LSB of a given number
    Given a positive integer N, the task is to find the number that can be obtained by flipping consecutive set bits starting from the LSB in the binary representation of N. Examples: Input: N = 39Output: 32Explanation:Binary representation of (39)10 = (100111)2After flipping all consecutive set bits st
    6 min read
    Count total unset bits in all the numbers from 1 to N
    Given a positive integer N, the task is to count the total number of unset bits in the binary representation of all the numbers from 1 to N. Note that leading zeroes will not be counted as unset bits.Examples: Input: N = 5 Output: 4 IntegerBinary RepresentationCount of unset bits11021013110410025101
    4 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