Problem:
Score : 600 points

Problem Statement

There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}.

The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds.

Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 would be concatenated into 37111519. What is the remainder when that integer is divided by M?

Constraints

All values in input are integers.

1 \leq L, A, B < 10^{18}

2 \leq M \leq 10^9

All terms in the arithmetic progression are less than 10^{18}.

Input

Input is given from Standard Input in the following format:

L A B M

Output

Print the remainder when the integer obtained by concatenating the terms is divided by M.

Sample Input 1

5 3 4 10007

Sample Output 1

5563

Our arithmetic progression is 3, 7, 11, 15, 19, so the answer is 37111519 mod 10007, that is, 5563.

Sample Input 2

4 8 1 1000000

Sample Output 2

891011

Sample Input 3

107 10000000000007 1000000000000007 998244353

Sample Output 3

39122908

Solution in Ruby (2.3.3) (judge verdict: Accepted)

def calc(r, n)
    res = 0
    sum = r
    base = 1
    bs = r
    while n > 0
        if n%2 == 1
            res += sum * base
            base *= bs
        end
        sum *= 1+bs
        bs *= bs
        n /= 2
        res %= MOD
        sum %= MOD
        base %= MOD
        bs %= MOD
    end
    res
end

def calc2(r, n)
    res = 0
    sum = r
    base = 1
    bs = r
    num = 0
    b = 1
    while n > 0
        if n%2 == 1
            res += (sum + num * calc(r, b)) * base
            num += b
            base *= bs
        end
        sum *= 1+bs
        sum += b * bs * calc(r, b)
        bs *= bs
        b *= 2
        n /= 2
        res %= MOD
        sum %= MOD
        base %= MOD
        bs %= MOD
    end
    res
end

def power_mod(num, power)
    prod = 1
    num %= MOD
    while power > 0 do
        if power & 1 == 1
            prod = (prod * num) % MOD
        end
        num = (num * num) % MOD
        power >>= 1
    end
    return prod
end

L, A, B, MOD = gets.split.map(&:to_i)
C = A + B*(L-1)

mn = 1
mx = 9
ans = 0
(1..18).each do |d|
    if d > 1
        mn *= 10
        mx = (mx+1) * 10 - 1
    end
    l = [0, (mn-A-1)/B+1].max
    r = [L-1, (mx-A)/B].min
    if l <= r
        rnum = A + B*r
        num = r-l+1
        ans *= power_mod(10, num*d)
        b = power_mod(10, d)
        ans += rnum * (1 + calc(b, num-1))
        ans -= B * calc2(b, num-1)
        ans %= MOD
    end
end
puts ans