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 (Clang 3.8.0) (judge verdict: Time Limit Exceeded)


#include <iostream>
#include <vector>
#include <string>
#include <numeric>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <queue>

#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;

long long factorial(long long i){ // 階乗
  if(i > 0)
    return i * factorial(i-1);
  else
    return 1;
}

// a^n mod
long long modpow(long long a, long long n, long long mod) {
  long long res = 1;
  while (n>0) {
    if(n & 1) res = res * a % mod;
    a = a * a % mod;
    n >>= 1;
  }
  return res;
}

// a^(-1) mod
long long modinv(long long a, long long mod) {
  return modpow(a, mod-2, mod);
}

int main() {
  long long L, A, B, M;
  cin >> L >> A >> B >> M;
  // 最大桁数を求める
  //long long max = A + (L-1) * B;
  long long max_keta = (long long)(log10(B)+log10(L-1 + ((double)A)/B));
  
  vector<long long> exp_mod;
  exp_mod.push_back(1); // 10^0%M;
  rep(i, max_keta+2) {
    long long tmp = exp_mod[i]*10 %M;
    exp_mod.push_back(tmp);
  }
  
  long long Amod = A%M;
  long long Bmod = B%M;
  
  long long ans = Amod;
  //cout << ans << endl;

  for(int i=1; i<L; i++) {
    long long keta =  (long long)(log10(B)+log10(i + ((double)A)/B));
    ans = ((ans * exp_mod[keta+1] %M + Amod)%M + (i%M)*Bmod)%M;
    //cout << ans << "  " << keta << endl;
  }
  
  cout << ans << endl;
  return 0;
}