Ask a Question

 

Start Coding Today

   

GeeksQuiz

GeeksforGeeksIDE

Data Structures

Algorithms

Interview Experiences

C Programming

C++ Programming

Java Programming

GATE CS

Books

Subsequences whose sum of digits is divisible by 6

Say I have a string whose characters are nothing but digits in [0 - 9] range. E.g: "2486". Now I want to find out all the subsequences whose sum of digits is divisible by 6. E.g: in "2486", the subsequences are - "6", "246" ( 2+ 4 + 6 = 12 is divisible by 6 ), "486" (4 + 8 + 6 = 18 is divisible by 6 ) etc. I know generating all 2^n combinations we can do this. But that's very costly. What is the most efficient way to do this?

asked Jul 8, 2015 by Kaushik

1 Answer

0 votes

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;
}
answered Oct 30, 2015 by gccode

Please log in or register to answer this question.

...