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 OCaml (4.02.3) (judge verdict: Wrong Answer)

let rec fold_for a b v f = if a >= b then v else fold_for (a+1) b (f a v) f

let rec pow ( * ) z a n =
  if n = 0 then z
  else if n mod 2 = 1 then a * (pow ( * ) z a (n-1))
  else let h = pow ( * ) z a (n/2) in h * h

let rec intpow = pow ( * ) 1

let i3 = [| [|1; 0; 0|]; [|0; 1; 0|]; [|0; 0; 1|] |]

let () =
  Scanf.scanf "%d %d %d %d" @@ fun l a b modulo ->
  
  let (+@) a b = (a + b + modulo) mod modulo in
  let modmul a b = (a * b) mod modulo in
  let modpow = pow modmul 1 in

  let matmul a b =
    let m = Array.length b in
    Array.init (Array.length a) (fun i ->
    Array.init (Array.length b.(0)) (fun j ->
      fold_for 0 m 0 (fun k s -> s +@ modmul a.(i).(k) b.(k).(j))))
  in

  let rec loop i d z =
    if i >= l then z else
    let j = (intpow 10 d - a - 1) / b |> min (l-1) in
    if a + b * j < intpow 10 (d-1) then loop i (d+1) z
    else ((
      let c = j-i+1 in
      let r = [| [| z; a +@ modmul b i; 1 |] |] in
      let m = [| [| modpow 10 d; 0; 0 |]; [| 1; 1; 0 |]; [| 0; b mod modulo; 1 |]; |] in
      let mc = pow matmul i3 m c in
      let r' = matmul r mc in
      loop (j+1) (d+1) r'.(0).(0)
    ))
  in

  loop 0 1 0 |> Printf.printf "%d\n"