Magic Five (Codeforces 327C)
Tags: Math, combinatorics

There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.Look at the input part of the statement, s is given in a special form.

Input: In the first line you're given a string a (1 ≤ |a| ≤ 105), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.

Output: Print a single integer — the required number of ways modulo 1000000007 (109 + 7).

Note: In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.

Sample Inputs:
1256
1

13990
2

555
2

Sample Outputs:
4

528

63

Solution (Python):
(t, k) = (input(), int(input()))
(s, n, d) = (0, 1, 1000000007)
for i in t:
    if i in '05':
        s += n
    n = (n << 1) % d
p = (pow(n, k, d) - 1) * pow(n - 1, d - 2, d)
print(p % d * (s % d) % d)

Solution (Python):
mod = 1000000007

def inv_mod(a, m):
    a %= m
    return pow(a, m - 2, m)
a = input()
k = int(input())
t = len(a)
d = 0
i = 1
for c in a:
    if c in ('0', '5'):
        d = (d + i) % mod
    i = i * 2 % mod
print(d * (pow(2, k * t, mod) - 1) * inv_mod(pow(2, t, mod) - 1, mod) % mod)

Solution (Python):
mod = 1000000007

def inv_mod(a, m):
    a %= m
    return pow(a, m - 2, m)
(a, k) = (input(), int(input()))
(t, d, i) = (len(a), 0, 1)
for c in a:
    if c in ('0', '5'):
        d = (d + i) % mod
    i = i * 2 % mod
print(d * (pow(2, k * t, mod) - 1) * inv_mod(pow(2, t, mod) - 1, mod) % mod)