Given a string of digits “0-9”. The task is find the number of substrings which are divisible by 8 but not by 3.
Input : str = "888" Output : 5 Substring indexes : (1, 1), (1, 2), (2, 2), (2, 3), (3, 3). Input : str = "6564525600" Output : 15
A number is divisible by 3 if sum of its digits is divisible by 3. And the number is divisible by 8 if last three digits are divisible by 8.
Now, the idea is to store the prefix sum of the string i.e count of prefixes such that sum of the digits of the prefix modulo 3 is either 0, 1, 2. Next we iterate over the string and for each position i, count the number of substrings ending at i and divisible by 8. From this value, we subtract the number of substrings ending at i and divisible by 3.
We define a |S| X 3 size 2D array, |S| is size of string, say dp[i][j].
dp[i][j] can be define as at any index i, number of substring starting from index 0 to index i having output j
when digits from index 0 are added upto index i and modulo 3. Therefore 0 <= j <= 2, since modulo 3. Now, we will iterate over string and check each one digit number, two digit number and three digit number which are divisible by 8. For one digit, just check if character at index is 8 or not. For two digit, check whether it is divisible by 8 and not divisible by 3. For three digit, form the number and check if it is divisible by 8 or not. If the number is divisible then last three digits must be divisible by 8. So all the substring ending at this index must be divisible by 8 i.e (i-3) substrings. But it will also contain those substring which are divisible by 3, so simply remove them using dp[i][j].
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of ordered pairs such that (Ai & Aj) = 0
- Number of n digit stepping numbers
- To check divisibility of any large number by 999
- Decimal representation of given binary string is divisible by 5 or not
- Program to count vowels in a string (Iterative and Recursive)
- Dynamic Programming | Building Bridges
- Toggle case of a string using Bitwise Operators
- Removing punctuations from a given string
- Minimum insertions to sort an array
- Program to remove vowels from a String
- Shortest Uncommon Subsequence
- Multiply Large Numbers represented as Strings
- Subset with sum divisible by m
- Number of substrings divisible by 6 in a string of integers
- Number of subsequences in a string divisible by n
Improved By : parashar