Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count all prefixes of the given binary array which are divisible by x in C++
In this tutorial, we will be discussing a program to find the number of prefixes of the binary array which are divisible by x.
For this we will be provided with binary array and a value x. Our task is to find the number of elements whose prefixes are divisible by given value x.
Example
#include <bits/stdc++.h>
using namespace std;
//counting the elements with prefixes
//divisible by x
int count_divx(int arr[], int n, int x){
int number = 0;
int count = 0;
for (int i = 0; i < n; i++) {
number = number * 2 + arr[i];
//increasing count
if ((number % x == 0))
count += 1;
}
return count;
}
int main(){
int arr[] = { 1, 0, 1, 0, 1, 1, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 2;
cout << count_divx(arr, n, x);
return 0;
}
Output
3
Advertisements
