GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Given an n-digit positive integer, count and print the number of subsequences formed by concatenating the given number's digits that are divisible by 8.

How will be the O(n) DP approach to solve this problem?

Please explain the algorithm or thought process

e.g. 3 no. of subsequences for 968

and 7 for 888={8,8,8,88,88,88,888}

P.S.This is a problem from HackerRank(Archived contest).Please do not post editorial

asked Jan 18 by anonymous

1 Answer

#define MOD 1000000007
#define MAXN    200000
long long F[2][8];
char S[MAXN+10];
int main()
{
    int N;
    scanf("%d", &N);
    scanf("%s", S);

    int digit;
    bool pre = 0;
    bool cur = 1;
    for (size_t i = 0; i < N; ++i) {

        digit = S[i] - '0';
            // here we do not consider S[i] so we just copy the previous value.
        for (int k = 0; k < 8; ++k) {
            F[cur][k] = F[pre][k];
        }

            // here we consider S[i], and only S[i] as a subsequence (length = 1)
        ++ F[cur][digit % 8];

            // here we add S[i] to all the subsequence and find the new remainder(val%8) and update 
            // the respective remainder. So, after this step number of subsequence giving remainder
            // j(from 0-8) will change.
            // eg: 968
            // s[i]=9. no of subsequence giving remainder 1 is 1 
            // s[i] 6. no of subsequence giving remainder 1 is 1, no of subsequence giving remainder 
            // 6 is 1, no of subsequence giving remainder 0 is 1(that is 96). and so on


        for (int k = 0; k < 8; ++k) {
            F[cur][(k * 10 + digit) % 8] += F[pre][k];
            F[cur][(k * 10 + digit) % 8] %= MOD;
        }

        pre = !pre;
        cur = !cur;
    }

    printf("%lld\n", F[pre][0] % MOD);
}

PS: JUST REMEMBER that dp[i][j] stores number of subsequence of giving the remainder j.let the subsequence be abcd and it gives a remainder x. we add e to the subsequence abcd and it becomes abcd10+e =abcde. take the modulo. (abcde)%mod or (abcd10+e)%mod or (x*10+e)%mod.

 

another method: https://www.hackerrank.com/contests/w28/challenges/lucky-number-eight/submissions/code/1300465668

answered Mar 2 by aMinuteMan
...