Any subsequence will be divisible by 6, if it is divisible by **2 and 3 both**.

For doing this... we have three variables

a0......number of subsequences divisible by 3.

a1......number of subsequences on dividing by 3 gives remainder 1.

a2......number of subsequences on dividing by 3 gives remainder 2.

If at any index a[i]%2==0 then all the subsequences ending at index i will be divisible by 2, So, we can add a0 to the answer, because these subsequences are divisible by both 2 and 3.

Here is the program.

Complexity: O(n).

#include <stdio.h>
#include <string.h>
int main(){
int i,n,a0=0,a1=0,a2=0,ans=0,previous=0;
int a[101];
char str[101];
scanf("%s",str);
n=strlen(str);
for(i=1;i<=n;i++){
a[i]=str[i]-'0';
a[i]%=6;
}
for(i=1;i<=n;i++){
if(a[i]%3==0){
a0*=2;
a1*=2;
a2*=2;
a0++;
}
else if(a[i]%3==1){
int b0=a0,b1=a1,b2=a2;
a0+=b2;
a1+=b0;
a2+=b1;
a1++;
}
else if(a[i]%3==2){
int b0=a0,b1=a1,b2=a2;
a0+=b1;
a1+=b2;
a2+=b0;
a2++;
}
if(a[i]%2==0)
ans+=a0-previous; // add a0-previous to answer because all these subsequences are divisible by both 2 and 3.
previous=a0; // store the previous value, because at next index we have to subtract this,to get number of subsequences ending at index i.
}
printf("%d\n",ans);
return 0;
}