Create an array of size len + 1 and initialize it with 0. Store remainders from left to right when divided by ' a '
int [ ] lr = new int [ len + 1 ] ; lr [ 0 ] = ( ( int ) str . charAt ( 0 ) - ( int ) '0' ) % a ; for ( int i = 1 ; i < len ; i ++ ) lr [ i ] = ( ( lr [ i - 1 ] * 10 ) % a + ( ( int ) str . charAt ( i ) - ( int ) '0' ) ) % a ;