Open In App

Decimal representation of given binary string is divisible by 5 or not

Last Updated : 20 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The problem is to check whether the decimal representation of the given binary number is divisible by 5 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or minimum number of multiplication and division operations. No leading 0’s are there in the input. 

Examples:

Input : 1010
Output : YES
(1010)2 = (10)10,
and 10 is divisible by 5.

Input : 10000101001
Output : YES
Recommended Practice

Approach: 

The following steps are:

  1. Convert the binary number to base 4.
  2. Numbers in base 4 contains only 0, 1, 2, 3 as their digits.
  3. 5 in base 4 is equivalent to 11.
  4. Now apply the rule of divisibility by 11 where you add all the digits at odd places and add all the digits at even places and then subtract one from the other. If the result is divisible by 11(which remember is 5), then the binary number is divisible by 5.

How to convert binary number to base 4 representation?

  1. Check whether the length of binary string is even or odd.
  2. If odd, the add ‘0’ in the beginning of the string.
  3. Now, traverse the string from left to right.
  4. One by extract substrings of size 2 and add their equivalent decimal to the resultant string.

Implementation:

C++
// C++ implementation to check whether decimal representation 
// of given binary number is divisible by 5 or not
#include <bits/stdc++.h>

using namespace std;

// function to return equivalent base 4 number 
// of the given binary number
int equivalentBase4(string bin)
{
    if (bin.compare("00") == 0) 
        return 0;
    if (bin.compare("01") == 0) 
        return 1;
    if (bin.compare("10") == 0) 
        return 2;
    return 3; 
}

// function to check whether the given binary
// number is divisible by 5 or not
string isDivisibleBy5(string bin)
{
    int l = bin.size();
    
    if (l % 2 != 0)
    // add '0' in the beginning to make 
    // length an even number
        bin = '0' + bin;
    
    // to store sum of digits at odd and 
    // even places respectively 
    int odd_sum, even_sum = 0;
    
    // variable check for odd place and
    // even place digit
    int isOddDigit = 1;
    for (int i = 0; i<bin.size(); i+= 2)
    {
        // if digit of base 4 is at odd place, then
        // add it to odd_sum
        if (isOddDigit)
            odd_sum += equivalentBase4(bin.substr(i, 2));
        // else digit of base 4 is at even place,
        // add it to even_sum 
        else
            even_sum += equivalentBase4(bin.substr(i, 2));
        
        isOddDigit ^= 1; 
    }
    
    // if this diff is divisible by 11(which is 5 in decimal)
    // then, the binary number is divisible by 5
    if (abs(odd_sum - even_sum) % 5 == 0)
        return "Yes";
    
    // else not divisible by 5
    return "No";
            
}

// Driver program to test above
int main()
{
    string bin = "10000101001";
    cout << isDivisibleBy5(bin);
    return 0;
} 
Java
//Java implementation to check whether decimal representation 
//of given binary number is divisible by 5 or not

class GFG 
{
    // Method to return equivalent base 4 number 
    // of the given binary number
    static int equivalentBase4(String bin)
    {
        if (bin.compareTo("00") == 0) 
            return 0;
        if (bin.compareTo("01") == 0) 
            return 1;
        if (bin.compareTo("10") == 0) 
            return 2;
        return 3; 
    }
    
    // Method to check whether the given binary
    // number is divisible by 5 or not
    static String isDivisibleBy5(String bin)
    {
        int l = bin.length();
        
        if (l % 2 != 0)
        // add '0' in the beginning to make 
        // length an even number
            bin = '0' + bin;
        
        // to store sum of digits at odd and 
        // even places respectively 
        int odd_sum=0, even_sum = 0;
        
        // variable check for odd place and
        // even place digit
        int isOddDigit = 1;
        for (int i = 0; i<bin.length(); i+= 2)
        {
            // if digit of base 4 is at odd place, then
            // add it to odd_sum
            if (isOddDigit != 0)
                odd_sum += equivalentBase4(bin.substring(i, i+2));
            // else digit of base 4 is at even place,
            // add it to even_sum 
            else
                even_sum += equivalentBase4(bin.substring(i, i+2));
            
            isOddDigit ^= 1; 
        }
        
        // if this diff is divisible by 11(which is 5 in decimal)
        // then, the binary number is divisible by 5
        if (Math.abs(odd_sum - even_sum) % 5 == 0)
            return "Yes";
        
        // else not divisible by 5
        return "No";
                
    }
    
    public static void main (String[] args)
    {
        String bin = "10000101001";
        System.out.println(isDivisibleBy5(bin));
    }
}
Python
# Python3 implementation to check whether 
# decimal representation of given binary 
# number is divisible by 5 or not

# function to return equivalent base 4 
# number of the given binary number 
def equivalentBase4(bin):
    if(bin == "00"):
        return 0
    if(bin == "01"):
        return 1
    if(bin == "10"):
        return 2
    if(bin == "11"):
        return 3
    
# function to check whether the given 
# binary number is divisible by 5 or not     
def isDivisibleBy5(bin):
    l = len(bin)
    if((l % 2) == 1):
        
    # add '0' in the beginning to 
    # make length an even number     
        bin = '0' + bin
        
    # to store sum of digits at odd 
    # and even places respectively 
    odd_sum = 0
    even_sum = 0
    isOddDigit = 1
    for i in range(0, len(bin), 2):
        
        # if digit of base 4 is at odd place, 
        # then add it to odd_sum 
        if(isOddDigit):
            odd_sum += equivalentBase4(bin[i:i + 2])
            
        # else digit of base 4 is at
        # even place, add it to even_sum     
        else:
            even_sum += equivalentBase4(bin[i:i + 2])
            
        isOddDigit = isOddDigit ^ 1

    # if this diff is divisible by 11(which is 
    # 5 in decimal) then, the binary number is
    # divisible by 5 
    if(abs(odd_sum - even_sum) % 5 == 0):
        return "Yes"
    else:
        return "No"

# Driver Code
if __name__=="__main__":
    bin = "10000101001"
    print(isDivisibleBy5(bin))

# This code is contributed 
# by Sairahul Jella 
C#
// C# implementation to check whether 
// decimal representation of given
// binary number is divisible by 5 or not 
using System;

class GFG
{
// Method to return equivalent base
// 4 number of the given binary number 
public static int equivalentBase4(string bin)
{
    if (bin.CompareTo("00") == 0)
    {
        return 0;
    }
    if (bin.CompareTo("01") == 0)
    {
        return 1;
    }
    if (bin.CompareTo("10") == 0)
    {
        return 2;
    }
    return 3;
}

// Method to check whether the 
// given binary number is divisible 
// by 5 or not 
public static string isDivisibleBy5(string bin)
{
    int l = bin.Length;

    if (l % 2 != 0)
    {
        // add '0' in the beginning to 
        // make length an even number 
        bin = '0' + bin;
    }

    // to store sum of digits at odd 
    // and even places respectively 
    int odd_sum = 0, even_sum = 0;

    // variable check for odd place 
    // and even place digit 
    int isOddDigit = 1;
    for (int i = 0; i < bin.Length; i += 2)
    {
        // if digit of base 4 is at odd 
        // place, then add it to odd_sum 
        if (isOddDigit != 0)
        {
            odd_sum += equivalentBase4(
                             bin.Substring(i, 2));
        }
        
        // else digit of base 4 is at even  
        // place, add it to even_sum 
        else
        {
            even_sum += equivalentBase4(
                              bin.Substring(i, 2));
        }

        isOddDigit ^= 1;
    }

    // if this diff is divisible by 
    // 11(which is 5 in decimal) then, 
    // the binary number is divisible by 5 
    if (Math.Abs(odd_sum - even_sum) % 5 == 0)
    {
        return "YES";
    }

    // else not divisible by 5 
    return "NO";

}

// Driver Code
public static void Main(string[] args)
{
    string bin = "10000101001";
    Console.WriteLine(isDivisibleBy5(bin));
}
}

// This code is contributed by Shrikant13
Javascript
<script>

// Javascript implementation to check whether
// decimal representation of given binary
// number is divisible by 5 or not

// function to return equivalent base 4
// number of the given binary number
function equivalentBase4(bin){
    if(bin == "00")
        return 0
    if(bin == "01")
        return 1
    if(bin == "10")
        return 2
    if(bin == "11")
        return 3
}
    
// function to check whether the given
// binary number is divisible by 5 or not    
function isDivisibleBy5(bin){
    let l = bin.length
    if((l % 2) == 1){
        
    // add '0' in the beginning to
    // make length an even number    
        bin = '0' + bin
    }
        
    // to store sum of digits at odd
    // and even places respectively
    let odd_sum = 0
    let even_sum = 0
    let isOddDigit = 1
    for(let i=0;i<bin.length;i+=2){
        
        // if digit of base 4 is at odd place,
        // then add it to odd_sum
        if(isOddDigit)
            odd_sum += equivalentBase4(bin.substring(i,i + 2))
            
        // else digit of base 4 is at
        // even place, add it to even_sum    
        else
            even_sum += equivalentBase4(bin.substring(i,i + 2))
            
        isOddDigit = isOddDigit ^ 1
    }

    // if this diff is divisible by 11(which is
    // 5 in decimal) then, the binary number is
    // divisible by 5
    if(Math.abs(odd_sum - even_sum) % 5 == 0)
        return "Yes"
    else
        return "No"
}

// Driver Code

let    bin = "10000101001"
document.writeln(isDivisibleBy5(bin))

// This code is contributed by shinjanpatra

</script>

Output
No

Time Complexity: O(n), where n is the number of digits in the binary number. 
Auxiliary Space: O(1)

Efficient & Simpler Approach


We can solve this problem in a much simpler way by leveraging the aptitude behind the unit digit & repeat sequence of powers of 2.

Approach:

1. A number is said to be divisible by 5 if its unit digit is either 0 or 5. For us to compute the units digit (in decimal form) of the given binary number, we need to do the generic, binary to decimal conversion but it’s an overkill because we are only interested in the unit digit.

2. So, to just compute the unit digit we need to find the summation of values which would contribute to the unit digit in the given binary to decimal conversion.

3. If we have a look at the powers of 2, they are, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096….

4. The unit digits of this powers of 2 series follow a repeat sequence, 2, 4, 8, 6.

5. Hence, we can make use of this repeat sequence in computing the unit digit (in decimal form) of the given binary number and then apply the divisibility rule of 5 on it.

Implementation:

C++
#include <iostream>
#include <string>
using namespace std;

string isDivisibleBy5(string bin)
{
    int size = bin.length();
    long long unitDigitDecimalValue = 0;
    if (bin[size - 1] == '1') {
        unitDigitDecimalValue += 1;
    }
    // The repeat sequence of powers of 2.
    int unitsDigit[] = { 2, 4, 8, 6 };
    // Index variable to track the repeat sequence.
    int repeatSequenceIndex = 0;
    // Logic to find the summation of all the unit digits.
    for (int i = size - 2; i >= 0; i--) {
        unitDigitDecimalValue
            += (bin[i] - '0')
               * unitsDigit[repeatSequenceIndex];
        repeatSequenceIndex = (repeatSequenceIndex + 1) % 4;
    }

    // We'll now check the divisibility rule on value of
    // units digit of the original input decimal number by
    // finding the '% 10' of the summation of all the unit
    // digits making up the original decimal number.
    if (((unitDigitDecimalValue % 10) == 0)
        || ((unitDigitDecimalValue % 10) == 5)) {
        return "Yes";
    }
    else {
        return "No";
    }
}

int main()
{
    string bin = "10000101001";
    cout << isDivisibleBy5(bin) << endl;
    return 0;
}

// This code is contributed by Shivam Gupta
Java
// Java implementation to check whether decimal
// representation of given binary number is divisible by 5 or
// not
import java.io.*;

class Solution {
    static String isDivisibleBy5(String bin)
    {
        // complete the function here
        int size = bin.length();
        long unitDigitDecimalValue = 0;
        if (bin.charAt(size - 1) == '1') {
            unitDigitDecimalValue += 1;
        }
        // The repeat sequence of powers of 2.
        int[] unitsDigit = { 2, 4, 8, 6 };
        // Index variable to track the repeat sequence.
        int repeatSequenceIndex = 0;
        // Logic to find the summation of all the unit
        // digits.
        for (int i = size - 2; i >= 0; i--) {
            unitDigitDecimalValue
                += (bin.charAt(i) - '0')
                   * unitsDigit[repeatSequenceIndex];
            repeatSequenceIndex
                = (repeatSequenceIndex + 1) % 4;
        }

        // We'll now check the divisibility rule on value of
        // units digit of the original input decimal number
        // by finding the '% 10' of the summation of all the
        // unit digits making up the original decimal number.
        if (((unitDigitDecimalValue % 10) == 0)
            || ((unitDigitDecimalValue % 10) == 5)) {
            return "Yes";
        }
        else {
            return "No";
        }
    }

    public static void main(String[] args)
    {
        String bin = "10000101001";
        System.out.println(isDivisibleBy5(bin));
    }
}
// This approach & code is contributed by Nikhil B.

Output
Yes

Time Complexity: O(n). where, ‘n’ is the number of digits in the given binary number.
Space Complexity: O(1).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads