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 pow(x, n, mod)
  ans = 1
  while n > 0
    ans = ans * x % mod if n.odd?
    x = x * x % mod
    n >>= 1
  end
  ans
end

def calc(a, b, d, n, mod)
  return 0 if n == 0
  acs, bcs, ms = [0, 0, 0]
  aa, bb, m = [0, 0, 0]
  while n > 0 do
    aa, bb, m = calc2(aa, bb, m, aa, bb, m, d, mod)
    aa, bb, m = [1, 0, 1] if m == 0
    acs, bcs, ms = calc2(aa, bb, m, acs, bcs, ms, d, mod) if n.odd?
    n >>= 1
  end
  (acs * a + bcs * b) % mod
end

def calc2(ac1, bc1, m1, ac2, bc2, m2, d, mod)
  [((pow(10, d * m2, mod) * ac1) % mod + ac2) % mod, ((pow(10, d * m2, mod) * bc1) % mod + ((m1 * ac2) % mod) + bc2) % mod, m1 + m2]
end

L, A, B, M = gets.chomp.split(" ").map(&:to_i)

E = []
a = Math.log10(A+1).ceil
s, i = [0, -1]
while(s < L) do
  s = ((10 ** a) - A - 1) / B
  E << (s >= L ? [a, L - 1, (L - 1 - i) * a] : [a, s, (s - i) * a])
  a += 1
  i = s
end

l = -1
ans = 0
E.each{|e|
  a, d, n, l = [A + (l + 1) * B, e[0], e[1] - l, e[1]]
  z = E.select{|e| e[0] > d}.inject(0){|rst, e| rst + e[2]}
  ans = ((calc(a, B, d, n, M) * pow(10, z, M)) % M + ans) % M
}

puts (ans % M)