ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อหาจำนวนพรีฟิกซ์ของอาร์เรย์ไบนารีที่หารด้วย x ลงตัว
สำหรับเรื่องนี้ เราจะได้รับอาร์เรย์ไบนารีและค่า x งานของเราคือหาจำนวนองค์ประกอบที่พรีฟิกซ์ของพวกเขาหารด้วยค่า x ที่กำหนดลงตัว
ตัวอย่าง
#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;
}เอาต์พุต
3