Count number of 1s in the array after N moves in C

CServer Side ProgrammingProgramming

We are given an array of size N. The array has all 0’s initially. The task is to count the no. of 1’s in the array after N moves. Each Nth move has a rule associated. The rules are −

  • 1st Move − Change element at positions 1, 2, 3, 4…………..

  • 2nd Move − Change element at positions 2, 4, 6, 8…………..

  • 3rd Move − Change element at positions 3, 6, 9, 12…………..

Count the number of 1’s in the last array.

Let’s understand with examples.

Input 

Arr[]={ 0,0,0,0 } N=4

Output 

Number of 1s in the array after N moves − 2

Explanation − Array after following moves −

Move 1: { 1,1,1,1 }
Move 2: { 1,0,1,0 }
Move 3: { 1,0,0,3 }
Move 4: { 1,0,0,1 }
Number of ones in the final array is 2.

Input 

Arr[]={ 0,0,0,0,0,0} N=6

Output 

Number of 1s in the array after N moves − 2

Explanation − Array after following moves −

Move 1: { 1,1,1,1,1,1,1 }
Move 2: { 1,0,1,0,1,0,1 }
Move 3: { 1,0,0,1,0,0,1 }
Move 4: { 1,0,0,0,1,0,0 }
Move 5: { 1,0,0,0,0,1,0 }
Move 4: { 1,0,0,0,0,0,1 }
Number of ones in the final array is 2.

Approach used in the below program is as follows

  • We take an integer array Arr[] initialized with 0’s and integer N.

  • Function Onecount takes Arr[] and it’s size N as input and returns no. of ones in the final array after N moves.

  • The for loop starts from 1 till the end of the array.

  • Each i represents the ith move.

  • Nested for loop starts from 0th index till end of array.

  • For each ith move, if the index j is multiple of i (j%i==0), replace the 0 with 1 at that position.

  • This process continues for each i till the end of array.

  • Note − Index starts from i=1,j=1 but array indexes are from 0 to N-1. For this reason arr[j1] is converted each time.

  • Finally traverse the whole array again and count no. of 1’s in it and store in count.

  • Return count as desired result.

Example

 Live Demo

#include <stdio.h>
int Onecount(int arr[], int N){
   for (int i = 1; i <= N; i++) {
      for (int j = i; j <= N; j++) {
         // If j is divisible by i
         if (j % i == 0) {
            if (arr[j - 1] == 0)
               arr[j - 1] = 1; // Convert 0 to 1
            else
               arr[j - 1] = 0; // Convert 1 to 0
         }
      }
   }
   int count = 0;
   for (int i = 0; i < N; i++)
      if (arr[i] == 1)
         count++; // count number of 1's
   return count;
}
int main(){
   int size = 6;
   int Arr[6] = { 0 };
   printf("Number of 1s in the array after N moves: %d", Onecount(Arr, size));
return 0;
}

Output

If we run the above code it will generate the following output −

Number of 1s in the array after N moves: 2
raja
Published on 17-Aug-2020 12:05:39
Advertisements