Open In App

Count all prefixes of the given binary array which are divisible by x

Last Updated : 09 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary array arr[] and an integer x, the task is to count all the prefixes of the given array which are divisible by x
Note: The ith prefix from arr[0] to arr[i] is interpreted as a binary number (from most-significant-bit to least-significant-bit.)
Examples: 
 

Input: arr[] = {0, 1, 0, 1, 1}, x = 5 
Output:
0 = 0 
01 = 1 
010 = 2 
0101 = 5 
01011 = 11 
0 and 0101 are the only prefixes divisible by 5.
Input: arr[] = {1, 0, 1, 0, 1, 1, 0}, x = 2 
Output:
 

 

Naive Approach: Iterate from 0 to i to convert each binary prefix to decimal and check whether the number is divisible by x or not.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count of total
// binary prefix which are divisible by x
int CntDivbyX(int arr[], int n, int x)
{
 
    // Initialize with zero
    int number = 0;
    int count = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Convert all prefixes to decimal
        number = number * 2 + arr[i];
 
        // If number is divisible by x
        // then increase count
        if ((number % x == 0))
            count += 1;
    }
 
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 0, 1, 0, 1, 1, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 2;
    cout << CntDivbyX(arr, n, x);
 
    return 0;
}


Java




// Java implementation of the approach
class GfG
{
 
    // Function to return the count of total
    // binary prefix which are divisible by x
    static int CntDivbyX(int arr[], int n, int x)
    {
     
        // Initialize with zero
        int number = 0;
        int count = 0;
     
        for (int i = 0; i < n; i++)
        {
     
            // Convert all prefixes to decimal
            number = number * 2 + arr[i];
     
            // If number is divisible by x
            // then increase count
            if ((number % x == 0))
                count += 1;
        }
     
        return count;
    }
 
    // Driver Code
    public static void main(String []args)
    {
         
        int arr[] = { 1, 0, 1, 0, 1, 1, 0 };
        int n = arr.length;
        int x = 2;
        System.out.println(CntDivbyX(arr, n, x));
    }
}
 
// This code is contributed by Rituraj Jain


Python3




# Python 3 implementation of the approach
 
# Function to return the count of total
# binary prefix which are divisible by x
def CntDivbyX(arr, n, x):
     
    # Initialize with zero
    number = 0
    count = 0
 
    for i in range(n):
         
        # Convert all prefixes to decimal
        number = number * 2 + arr[i]
 
        # If number is divisible by x
        # then increase count
        if ((number % x == 0)):
            count += 1
 
    return count
 
# Driver code
if __name__ == '__main__':
    arr = [1, 0, 1, 0, 1, 1, 0]
    n = len(arr)
    x = 2
    print(CntDivbyX(arr, n, x))
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# implementation of the approach
using System;
 
class GfG
{
 
    // Function to return the count of total
    // binary prefix which are divisible by x
    static int CntDivbyX(int[] arr, int n, int x)
    {
     
        // Initialize with zero
        int number = 0;
        int count = 0;
     
        for (int i = 0; i < n; i++)
        {
     
            // Convert all prefixes to decimal
            number = number * 2 + arr[i];
     
            // If number is divisible by x
            // then increase count
            if ((number % x == 0))
                count += 1;
        }
     
        return count;
    }
 
    // Driver Code
    public static void Main()
    {
         
        int[] arr = { 1, 0, 1, 0, 1, 1, 0 };
        int n = arr.Length;
        int x = 2;
        Console.WriteLine(CntDivbyX(arr, n, x));
    }
}
 
// This code is contributed by Code_Mech.


PHP




<?php
// PHP implementation of the approach
 
// Function to return the count of total
// binary prefix which are divisible by x
function CntDivbyX($arr, $n, $x)
{
 
    // Initialize with zero
    $number = 0;
    $count = 0;
 
    for ($i = 0; $i < $n; $i++)
    {
 
        // Convert all prefixes to decimal
        $number = $number * 2 + $arr[$i];
 
        // If number is divisible by x
        // then increase count
        if (($number % $x == 0))
            $count += 1;
    }
 
    return $count;
}
 
// Driver code
$arr = array(1, 0, 1, 0, 1, 1, 0);
$n = sizeof($arr);
$x = 2;
echo CntDivbyX($arr, $n, $x);
 
// This code is contributed by Akanksha Rai


Javascript




<script>
// Javascript implementation of the approach
 
// Function to return the count of total
// binary prefix which are divisible by x
function CntDivbyX(arr, n, x)
{
 
    // Initialize with zero
    let number = 0;
    let count = 0;
 
    for (let i = 0; i < n; i++) {
 
        // Convert all prefixes to decimal
        number = number * 2 + arr[i];
 
        // If number is divisible by x
        // then increase count
        if ((number % x == 0))
            count += 1;
    }
 
    return count;
}
 
// Driver code
    let arr = [ 1, 0, 1, 0, 1, 1, 0 ];
    let n = arr.length;
    let x = 2;
    document.write(CntDivbyX(arr, n, x));
 
</script>


Output: 

3

 

Time Complexity: O(N) where N is the size of the array
Auxiliary Space: O(1)

Efficient Approach: As we see in the above approach we convert each binary prefix to a decimal number like 0, 01, 010, 0101…. but as the value of n(size of array) increases then the resultant number will be very large and no. will be out of range of data type, so we can make use of the modular properties. 
Instead of doing number = number * 2 + arr[ i ] , we can do better as number = (number * 2 + arr[ i ] ) % x 
Explanation: We start with number = 0 and repeatedly do number = number * 2 + arr[ i ] then in each iteration we’ll get a new term of the above sequence. 
 

A = {1, 0, 1, 0, 1, 1, 0} 
“1” = 0*2 + 1 = 1 
“10” = 1*2 + 0 = 2 
“101” = 2*2 + 1 = 5 
“1010” = 5*2 + 0 = 10 
“10101” = 10*2 + 1 = 21 
“101011” = 21*2 + 1 = 43 
“1010110” = 43*2 + 0 =86 
 

Since we are repeatedly taking the remainders of the number at each step, at each step we have, newNum = oldNum * 2 + arr[i] .By the rules of modular arithmetic (a * b + c) % m is same as ((a * b) % m + c % m) % m. So, it doesn’t matter whether oldNum is the remainder or the original number, the answer would be correct. 
Note: Similar article discussed here.
Below is the implementation of the above approach:
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count of total
// binary prefix which are divisible by x
int CntDivbyX(int arr[], int n, int x)
{
 
    // Initialize with zero
    int number = 0;
    int count = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Instead of converting all prefixes
        // to decimal, take reminder with x
        number = (number * 2 + arr[i]) % x;
 
        // If number is divisible by x
        // then reminder = 0
        if (number == 0)
            count += 1;
    }
 
    return count;
}
 
// Driver code
int main()
{
 
    int arr[] = { 1, 0, 1, 0, 1, 1, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 2;
    cout << CntDivbyX(arr, n, x);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG {
 
    // Function to return the count of total
    // binary prefix which are divisible by x
    public static int CntDivbyX(int arr[], int n, int x)
    {
 
        // Initialize with zero
        int number = 0;
        int count = 0;
 
        for (int i = 0; i < n; i++) {
 
            // Instead of converting all prefixes
            // to decimal, take reminder with x
            number = (number * 2 + arr[i]) % x;
 
            // If number is divisible by x
            // then reminder = 0
            if (number == 0)
                count += 1;
        }
 
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 0, 1, 0, 1, 1, 0 };
        int n = 7;
        int x = 2;
        System.out.print(CntDivbyX(arr, n, x));
    }
}


Python3




# Python3 implementation of the approach
 
# Function to return the count of total
# binary prefix which are divisible by x
def CntDivbyX(arr, n, x):
 
    number = 0
 
    count = 0
 
    for i in range (0, n):
         
        # Instead of converting all prefixes
        # to decimal, take reminder with x
        number = ( number * 2 + arr[i] ) % x
     
        # If number is divisible by x
        # then reminder = 0
        if number == 0:
            count += 1
     
    return count
 
# Driver code
arr = [1, 0, 1, 0, 1, 1, 0]
n = 7
x = 2
print( CntDivbyX(arr, n, x) )


C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the count of total
    // binary prefix which are divisible by x
    public static int CntDivbyX(int []arr, int n, int x)
    {
 
        // Initialize with zero
        int number = 0;
        int count = 0;
 
        for (int i = 0; i < n; i++)
        {
 
            // Instead of converting all prefixes
            // to decimal, take reminder with x
            number = (number * 2 + arr[i]) % x;
 
            // If number is divisible by x
            // then reminder = 0
            if (number == 0)
                count += 1;
        }
 
        return count;
    }
 
    // Driver code
    public static void Main()
    {
        int []arr = { 1, 0, 1, 0, 1, 1, 0 };
        int n = 7;
        int x = 2;
         
        Console.Write(CntDivbyX(arr, n, x));
    }
}
 
// This code is contributed by Ryuga


PHP




<?php
// PHP implementation of the approach
 
// Function to return the count of total
// binary prefix which are divisible by x
function CntDivbyX($arr, $n, $x)
{
 
    // Initialize with zero
    $number = 0;
    $count1 = 0;
 
    for ($i = 0; $i < $n; $i++)
    {
 
        // Instead of converting all prefixes
        // to decimal, take reminder with x
        $number = ($number * 2 + $arr[$i]) % $x;
 
        // If number is divisible by x
        // then reminder = 0
        if ($number == 0)
            $count1 += 1;
    }
 
    return $count1;
}
 
// Driver code
$arr = array(1, 0, 1, 0, 1, 1, 0);
$n = sizeof($arr);
$x = 2;
echo CntDivbyX($arr, $n, $x);
 
// This code is contributed by Akanksha Rai
?>


Javascript




<script>
// Javascript implementation of the approach
 
// Function to return the count of total
// binary prefix which are divisible by x
function CntDivbyX(arr, n, x)
{
 
    // Initialize with zero
    let number = 0;
    let count = 0;
 
    for (let i = 0; i < n; i++) {
 
        // Instead of converting all prefixes
        // to decimal, take reminder with x
        number = (number * 2 + arr[i]) % x;
 
        // If number is divisible by x
        // then reminder = 0
        if (number == 0)
            count += 1;
    }
 
    return count;
}
 
// Driver code
 
    let arr = [ 1, 0, 1, 0, 1, 1, 0 ];
    let n = arr.length;
    let x = 2;
    document.write(CntDivbyX(arr, n, x));
 
</script>


Output: 

3

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 



Similar Reads

Check if all prefixes of a number is divisible by remaining count of digits
Given a number N, the task is to check if for every value of i (0 &lt;= i &lt;= len), the first i digits of a number is divisible by (len - i + 1) or not, where len is the number of digits in N. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: N = 52248.Output: YesExplanation: 5 is divisible by 552 is divisible by 4522
4 min read
Python | Count all prefixes in given string with greatest frequency
Given a string, print and count all prefixes in which first alphabet has greater frequency than second alphabet.Take two alphabets from the user and compare them. The prefixes in which the alphabet given first has greater frequency than the second alphabet, such prefixes are printed, else the result will be 0. Examples : Input : string1 = "geek", a
4 min read
Find permutation which generates lexicographically largest Array of GCD of Prefixes
Given an array A[] of size N, find the permutation of array A such that the array B[] which is formed by taking the GCD of the prefixes of array A is lexicographically greatest among all possible arrays. Print the permutation of A and also B. Note: If multiple answers are possible, print any of them Examples: Input: A[] = {2, 1, 4, 8, 16, 32, 5}Out
17 min read
Count of Strings of Array having given prefixes for Q query
Given two arrays of strings containing words[] and queries[] having N and Q strings respectively, the task is to find the number of strings from words[] having queries[i] as the prefix for all the strings in queries[]. Examples: Input: words[] = { "geeks", "geeks", "geeks for geeks", "string", "strong" }, queries[] = { "geek", "gel", "str" }Output:
13 min read
Print N-bit binary numbers having more 1’s than 0’s in all prefixes
Given a positive integer n, print all n-bit binary numbers having more 1’s than 0’s for any prefix of the number. Examples: Input : n = 2 Output : 11 10 Input : n = 4 Output : 1111 1110 1101 1100 1011 1010Recommended PracticePrint N-bit binary numbers having more 1s than 0sTry It! A simple but not efficient solution will be to generate all N-bit bi
13 min read
Minimum count of prefixes and suffixes of a string required to form given string
Given two strings str1 and str2, the task is to find the minimum number of prefixes and suffixes of str2 required to form the string str1. If the task is not possible, return "-1". Example: Input: str1 = "HELLOWORLD", str2 = "OWORLDHELL"Output: 2Explanation: The above string can be formed as "HELL" + "OWORLD" which are suffix and prefix of the stri
10 min read
Count of N digit numbers not having given prefixes
Given an integer N and a vector of strings prefixes[], the task is to calculate the total possible strings of length N from characters '0' to '9'. such that the given prefixes cannot be used in any of the strings. Examples: Input: N = 3, prefixes = {"42"}Output: 990Explanation: All string except{"420", "421", "422", "423", "424", "425", "426", "427
8 min read
Shift all prefixes by given lengths
Given a string S containing letters and digits, and an integer array Shift where, [Tex]1 \leq S.length()=length(Shift) \leq 10^{5} [/Tex]and for each element of Shift array [Tex]0 \leq Shift[i] \leq 10^{9} [/Tex]. The task is, for each Shift[i] = X, you have to shift the first i+1 letters of S, X times. Return the final string after all applying al
6 min read
Length of all prefixes that are also the suffixes of given string
Given a string S consisting of N characters, the task is to find the length of all prefixes of the given string S that are also suffixes of the same string S. Examples: Input: S = "ababababab"Output: 2 4 6 8Explanation: The prefixes of S that are also its suffixes are: "ab" of length = 2"abab" of length = 4"ababab" of length = 6"abababab" of length
10 min read
Sum of all prefixes of given numeric string
Given string str having N characters representing an integer, the task is to calculate the sum of all possible prefixes of the given string. Example: Input: str = "1225"Output: 1360Explanation: The prefixes of the given string are 1, 12, 122, and 1225 and their sum will be 1 + 12 + 122 + 1225 = 1360. Input: str = "20"Output: 22 Approach: The given
8 min read
Practice Tags :