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)

n, a, b, md = gets.split.map(&:to_i)

def getlen(a)
  res = 0
  while a > 0
    res += 1
    a /= 10
  end
  res
end

def modpow(a, b, md)
  res = 1
  while b > 0 
    if b.odd? 
      res = res * a % md
    end
    a = a * a % md
    b /= 2
  end
  res
end

def modpowsum(r, n, md)
  return 0 if n == 0
  if n.odd?
    return (1 + modpowsum(r, n - 1, md) * r) % md
  end
  x = modpowsum(r, n / 2, md)
  return x * (1 + modpow(r, n / 2, md)) % md
end

def modpowsum2(r, n, md)
  if n == 0
    return 0
  end
  if n.odd?
    return (n - 1 + modpowsum2(r, n - 1, md) * r) % md
  end
  x = modpowsum2(r, n / 2, md)
  return (x * modpow(r, n / 2, md) + x + modpowsum(r, n / 2, md) * n / 2) % md
end

k = 0
ans = 0

while k < n
  l = k
  r = n
  while r - l > 1
    m = (l + r) / 2
    if getlen(a + m * b) == getlen(a + k * b)
      l = m
    else
      r = m
    end
  end
  len = getlen(a + k * b) * (r - k)
  ans = ans * modpow(10, len, md) % md

  x = modpow(10, getlen(a + k * b), md)
  ans += (a + b * k) * modpowsum(x, r - k, md)
  ans += b * modpowsum2(x, r - k, md)
# a * modpowsum(x, r - k, md) + b * modpowsum2(x, r - k
  ans %= md
  k = r
end

puts ans