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 C# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;

class F
{
	static void Main()
	{
		var h = Array.ConvertAll(Console.ReadLine().Split(), long.Parse);
		long l = h[0], a = h[1], b = h[2];
		M = h[3];

		long r = 0, n_min = 0;
		var d_max = (a + (l - 1) * b).ToString().Length;
		for (int d = a.ToString().Length; d <= d_max; d++)
		{
			var d10 = 1L;
			for (int i = 0; i < d; i++) d10 *= 10;
			var n_max = Math.Min(l - 1, (d10 - 1 - a) / b);

			long c = a + n_min * b, n = n_max - n_min + 1;
			n_min = ++n_max;

			var q = new[,] { { d10 % M, 1, 0 }, { 0, 1, 1 }, { 0, 0, 1 } };
			var qn = MPow(q, n);
			r = MMul(qn, new[] { r, c % M, b % M })[0];
		}
		Console.WriteLine(r);
	}

	static long M;

	static long[,] UnitMatrix(int n)
	{
		var r = new long[n, n];
		for (int i = 0; i < n; i++) r[i, i] = 1;
		return r;
	}

	static long[,] MPow(long[,] b, long i)
	{
		for (var r = UnitMatrix(b.GetLength(0)); ; b = MMul(b, b))
		{
			if (i % 2 > 0) r = MMul(r, b);
			if ((i /= 2) < 1) return r;
		}
	}

	static long[,] MMul(long[,] a, long[,] b)
	{
		var n = a.GetLength(0);
		var r = new long[n, n];
		for (var i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				for (var k = 0; k < n; k++)
					r[i, j] = (r[i, j] + a[i, k] * b[k, j]) % M;
		return r;
	}

	static long[] MMul(long[,] a, long[] v)
	{
		var n = v.Length;
		var r = new long[n];
		for (var i = 0; i < n; i++)
			for (var k = 0; k < n; k++)
				r[i] = (r[i] + a[i, k] * v[k]) % M;
		return r;
	}
}