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++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <iostream>
#include <utility>
using namespace std;

__int128 mod_pow(__int128 x, __int128 k, __int128 mod){
  __int128 ret = 1;
  while(k){
    if(k&1) ret *= x, ret %= mod;
    x *= x, x %= mod;
    k >>= 1;
  }
  return ret;
}
 
// __int128 rec(__int128 x, __int128 k, __int128 mod){
//   if(k == 1) return 1;
//   __int128 ret = rec(x,k/2,mod)*(1+mod_pow(x,k/2,mod))%mod;
//   if(k%2) ret += mod_pow(x,k-1,mod), ret %= mod;
//   return ret;
// }

pair<__int128, __int128> rec(__int128 x, __int128 k, __int128 mod){
  if(k == 1) return {1,0};
  pair<__int128,__int128> p = rec(x,k/2,mod);
  __int128 f = p.first, s = p.second;
  __int128 f_ = f*(1+mod_pow(x,k/2,mod))%mod;
  if(k%2) f_ += mod_pow(x,k-1,mod), f_ %= mod;
  __int128 s_ = (s + (s+f*(k/2)%mod)%mod*mod_pow(x,k/2,mod)%mod)%mod;
  if(k%2) s_ += (k-1)%mod*mod_pow(x,k-1,mod)%mod, s_ %= mod;
  return {f_,s_};
}

int main(){
  long long L_, A_, B_, M_;
  cin >> L_ >> A_ >> B_ >> M_;
  __int128 L = L_, A = A_, B = B_, M = M_;
  A += B*(L-1);
  B *= -1;
  constexpr int max_len = 18;
  __int128 s = 0;
  __int128 ans = 0;
  __int128 D[max_len+1];
  D[0] = 1;
  for(int k = 0; k < max_len; ++k) D[k+1] = (D[k]*10);
  // for(int k = 0; k <= 10; ++k){
  int prev_r = 0;
  for(int k = max_len; k >= 0; --k){
    __int128 d_ = D[k];
    __int128 l = prev_r, r = (A-d_)/(-B) + 1;
    r = max(l,r);
    r = min(L,r);

    // cerr << k << " " << l << " " << r << endl;
    // cerr << s << endl;
    
    if(l < r){
      pair<__int128,__int128> p = rec(mod_pow(10,k+1,M),r-l,M);
      __int128 t = p.first*(((A%M+((B%M)*l)%M)%M+M)%M)%M;
      t += ((p.second*(B%M))%M+M)%M;
      t %= M;
      t *= mod_pow(10,s,M);
      t %= M;
      ans += t;
      ans %= M;
      s += (r-l)*(k+1);
    }
    prev_r = r;
  }
  cout << (long long)ans << endl;
}