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.
Input : 1010
Output : YES
(1010)2 = (10)10,
and 10 is divisible by 5.
Input : 10000101001
Output : YES
Numbers in base 4 contains only 0, 1, 2, 3 as their digits.
5 in base 4 is equivalent to 11.
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?
Check whether the length of binary string is even or odd.
If odd, the add ‘0’ in the beginning of the string.
Now, traverse the string from left to right.
One by extract substrings of size 2 and add their equivalent decimal to the resultant string.
// C++ 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
if(bin.compare("00") == 0)
if(bin.compare("01") == 0)
if(bin.compare("10") == 0)
// function to check whether the given binary
// number is divisible by 5 or not
string isDivisibleBy5(string bin)
intl = 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
intodd_sum, even_sum = 0;
// variable check for odd place and
// even place digit
intisOddDigit = 1;
for(inti = 0; i<bin.size(); i+= 2)
// if digit of base 4 is at odd place, then
// add it to odd_sum
odd_sum += equivalentBase4(bin.substr(i, 2));
// else digit of base 4 is at even place,
// add it to even_sum
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)
// else not divisible by 5
// Driver program to test above
string bin = "10000101001";
cout << isDivisibleBy5(bin);
//Java implementation to check whether decimal representation
Time Complexity: O(n), where n is the number of digits in the binary number. Auxiliary Space: O(1)
This article is contributed by Aarti_Rathi and Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...