- Combinatorial, combionatrics, divisibility, Mathematical, number-digits, Strings

Count ways to make the number formed by K concatenations of a numeric string divisible by 5

Given a string S consisting of N digits and an integer K, the task is to count the number of ways to remove digits from the number formed by the concatenating the string S, K number of times, such that the resulting string is divisible by 5. Since count can be very large, so print it to modulo 109 + 7.Examples:Input: S = 1256, K = 1Output: 4Explanation:Following are the ways to remove the characters so that the string S(= “1256”) is divisible by 5:Remove the character 6 from the string S modifies the string to 125, which is divisible by 5.Remove the character 1, and 6 from the string S modifies the string to 25, which is divisible by 5.Remove the character 2, and 6 from the string S modifies the string to 15, which is divisible by 5.Remove the character 1, 2, and 6 from the string S modifies the string to 5, which is divisible by 5.Therefore, the total count of numbers formed which is divisible by 5 is 4.Input: S = 13390, K = 2Output: 528Approach: The given problem can be solved by the fact that the number is divisible by 5 if and only if its last digit is either 0 or 5. If sol[i] is the number of ways to form the numbers divisible by 5 ending at i, then the count of numbers is given by (sol[1] + sol[2] + … + sol[N]). For each index i, on the right of i, the choice is to delete all digits and on the left of i, then there are two choices, either to delete or to take i.e., 2(i – 1). Therefore, the total count of numbers for K number of concatenation is given by:ans = ans * (2(K*N) -1) / (2N – 1)Below is the implementation of the above approach: C++  #include using namespace std;typedef long long LL;const int MOD = 1000000007;  int exp_mod(LL a, LL b){          LL ret = 1;          for (; b; b >>= 1, a = a * a % MOD) {        if (b & 1)            ret = ret * a % MOD;    }      return ret;}  int countOfWays(string s, int k){    int N = s.size();          LL ans = 0;          for (int i = 0; i < N; i++) {                  if (s[i] == '5' || s[i] == '0') {            ans = (ans + exp_mod(2, i)) % MOD;        }    }              LL q = exp_mod(2, N);    LL qk = exp_mod(q, k);    LL inv = exp_mod(q - 1, MOD - 2);          ans = ans * (qk - 1) % MOD;    ans = ans * inv % MOD;      return ans;}  int main(){    string S = "1256";    int K = 1;    cout