Number of substrings divisible by 8 but not by 3 | Java program to count substrings which are divisible by 8 but not by 3 ; Function that returns count of substrings divisible by 8 but not by 3 ; Iterating the string . ; Prefix sum of number of substrings whose sum of digits mudolo 3 is 0 , 1 , 2. ; Iterating the string . ; Since single digit 8 is divisible by 8 and not by 3. ; Taking two digit number . ; 10 th position ; Complete 2 digit ; Taking 3 digit number . ; 100 th position ; 10 th position ; Complete 3 digit number . ; If number formed is divisible by 8 then last 3 digits are also divisible by 8. Then all the substring ending at this index is divisible . ; But those substring also contain number which are not divisible by 3 so remove them . ; driver program
import java . io . * ; class GFG { static int count ( String s , int len ) { int MAX = 1000 ; int cur = 0 , dig = 0 ; int [ ] sum = new int [ MAX ] ; int [ ] [ ] dp = new int [ MAX ] [ 3 ] ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= len ; i ++ ) { dig = ( int ) ( s . charAt ( i - 1 ) ) - 48 ; cur += dig ; cur %= 3 ; sum [ i ] = cur ; dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] ; dp [ i ] [ 1 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 2 ] = dp [ i - 1 ] [ 2 ] ; dp [ i ] [ sum [ i ] ] ++ ; } int ans = 0 , dprev = 0 , value = 0 , dprev2 = 0 ; for ( int i = 1 ; i <= len ; i ++ ) { dig = ( int ) ( s . charAt ( i - 1 ) ) - 48 ; if ( dig == 8 ) ans ++ ; if ( i - 2 >= 0 ) { dprev = ( int ) ( s . charAt ( i - 2 ) ) - 48 ; value = dprev * 10 + dig ; if ( ( value % 8 == 0 ) && ( value % 3 != 0 ) ) ans ++ ; } if ( i - 3 >= 0 ) { dprev2 = ( int ) ( s . charAt ( i - 3 ) ) - 48 ; dprev = ( int ) ( s . charAt ( i - 2 ) ) - 48 ; value = dprev2 * 100 + dprev * 10 + dig ; if ( value % 8 != 0 ) continue ; ans += ( i - 2 ) ; ans -= ( dp [ i - 3 ] [ sum [ i ] ] ) ; } } return ans ; } public static void main ( String [ ] args ) { String str = "6564525600" ; int len = str . length ( ) ; System . out . println ( count ( str , len ) ) ; } }