Problem:


Score : 600 points

Problem Statement
Q tuples of integers (L_i, A_i, B_i, M_i). For each tuple, answer the following question. -->

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



Sample input:
5 3 4 10007


Sample output:
5563

Submission status: Time Limit Exceeded

Solution code:
from math import ceil
def dot(a,b,m):
    c = [[0,0,0],[0,0,0],[0,0,0]]
    for i in range(3):
        for j in range(3):
            for k in range(3):
                c[i][j] += a[i][k]*b[k][j]
                c[i][j] %= m
    return c
def powm(a,n,m):
    if n == 0:
        return [[1,0,0],[0,1,0],[0,0,1]]
    for i in range(3):
        for j in range(3):
            a[i][j] %= m
    if n%2==0:
        return dot(powm(a,n//2,m),powm(a,n//2,m),m)
    else:
        return dot(dot(powm(a,n//2,m),powm(a,n//2,m),m),a,m)

L,A,B,M = map(int,input().split())

a = [[1,0,0],[0,1,0],[0,0,1]]
for d in range(1,19):
    C = min(max(0,ceil((10**d-A)/B)),L)-min(max(0,ceil((10**(d-1)-A)/B)),L)
    a = dot(powm([[pow(10,d,M),1,0],[0,1,B%M],[0,0,1]],C,M),a,M)
ans = (a[0][1]*A+a[0][2])%M
print(ans)

Submission status: Time Limit Exceeded

Solution code:
L, A, B, M = map(int, input().split())
num = ''
for i in range(L):
    num += str(A + B * i)
print(int(num) % M)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = (int(x) for x in input().split())
Sstr = []
answer = 0
for i in range(L):
  Sstr.append(str(A + B * i))
  
S = "".join(Sstr)
#print(S)
answer = int(S) % M
print(answer)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron, log
from fractions import gcd as pg 
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
f5=lambda : raw_input().split()


def main():
    l,a,b,di=f1()
    s=""
    n=0
    n1=len(str(di))
    for i in xrange(0,l+1):
        if i<l:
            t=str(a+b*i)
            n=n+len(t)
            s=s+t

        while n>=n1:
            k=int(s[:n1])
            s=s[n1:]
            n=n-n1
            if k<di:
                if s=='':
                    s=str(k)
                else:
                    k=int(str(k)+s[0])
                    s=s[1:]
                    n=n-1
            if k>=di:
                ans=k%di
                s=str(ans)+s
            n=len(s)

    print s



    


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
L, A, B, M = input().split()
data = ""
for i in range(int(L)):
  d = int(A) + int(B)*i
  data += str(d)
ans = int(data)%int(M)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def takahashi(l,a,b,m):
    suretsu=[]
    suretsu.append(a)
    for i in range(l-1):
        s = a+b*(i+1)
        suretsu.append(s)

    suji=int("".join(map(str, suretsu)))

    print(suji%m)

l,a,b,m = map(int,input().split())
takahashi(l,a,b,m)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import math
INF = float("inf")


def pow(base, n, mod):
    ans = 1
    while n > 0:
        if n % 2 == 1:
            ans *= base
            ans %= mod
        base *= base
        base %= mod
        n //= 2
    return ans


def solve(L: int, A: int, B: int, M: int):

    # s = A
    # ans = s % M
    # for l in range(L-1):
    #     new_s = (s+B) % M
    #     # print(s, new_s)
    #     keta = int(math.log10(new_s)+1)
    #     # print("keta", keta, ans)
    #     ans = ans*((10**keta) % M)
    #     ans %= M
    #     ans += new_s
    #     ans %= M
    #     s = new_s
    #     print(ans)

    ans = 0
    s = A-B
    for l in range(L):
        s += B
        ans *= pow(10, int(math.log10(s)+1), M)
        ans %= M
        ans += s
        ans %= M
    print(ans)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    L = int(next(tokens))  # type: int
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    solve(L, A, B, M)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import math
INF = float("inf")


def pow(base, n, mod):
    ans = 1
    while n > 0:
        ans *= base
        ans %= mod
        n -= 1
    return ans


def solve(L: int, A: int, B: int, M: int):

    # s = A
    # ans = s % M
    # for l in range(L-1):
    #     new_s = (s+B) % M
    #     # print(s, new_s)
    #     keta = int(math.log10(new_s)+1)
    #     # print("keta", keta, ans)
    #     ans = ans*((10**keta) % M)
    #     ans %= M
    #     ans += new_s
    #     ans %= M
    #     s = new_s
    #     print(ans)

    ans = 0
    s = A-B
    for l in range(L):
        s += B
        ans *= pow(10, int(math.log10(s)+1), M)
        ans %= M
        ans += s
        ans %= M
    print(ans)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    L = int(next(tokens))  # type: int
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    solve(L, A, B, M)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- encoding: utf-8 -*-
import sys
import re
import random
import numpy as np
from math import sqrt,log
from fractions import gcd  # python<=3.4
from collections import Counter, defaultdict

MOD = 1000000007


def solve(l,a,b,m):
    q = []
    k = 1
    mx = 9
    x = a
    rem = l
    while True:
        # print '// k=%d, mx=%d, x=%d, rem=%d' % (k,mx,x,rem)
        if x <= mx:
            lo = x
            cnt = int((mx - lo)/b) + 1
            if cnt > rem:
                cnt = rem
            hi = lo + b*(cnt-1)
            q.append( (k,cnt,hi,lo) )
            rem -= cnt
            if rem == 0:
                break
            x = hi + b
            # print '// x=%d, mx=%d' % (x, mx)
            assert mx < x
        mx = mx*10 + 9
        k += 1
    q.reverse()
    # k,cnt,hi,lo
    ans = 0
    right = 0

    def s(x, n):
        y = (x ** (n+1) - 1) / (x - 1)
        return y
    def t(x, n):
        y = s(x,n)-1 - n*(d ** (n+1))
        z = y / (1 - d)
        return z

    G = 1
    for k,cnt,hi,lo in q:
        # print "G=%d k=%d cnt=%d ; %d..%d" % (G,k,cnt,lo,hi)
        d = 10 ** k
        u = hi * s(d, cnt-1)
        u -= b * t(d, cnt-1)
        ans += G * u

        right += k * cnt  # 右の桁数
        G = 10 ** right

    return ans % m

l,a,b,m = map(int, raw_input().rstrip().split())
print solve(l,a,b,m)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = map(int, input().split())
nums = [(A+B*i)%M for i in range(L)]
idx = 0
idxs = [0]
for i in range(L-1):
    idx += len(str(A+B*(L-1-i)))
    idxs.append(idx)
Z=0
for i in range(L):
    Z += (nums[i] * (10**idxs[L-1-i] % M)) %M
print(Z%M)

Submission status: Time Limit Exceeded

Solution code:
inp = input().split()
L = int(inp[0])
A = int(inp[1])
B = int(inp[2])
M = int(inp[3])

summ = int(''.join([str(i) for i in range(A, 1000000000000000000000000000000000000000, B)[:L]]))
print(summ%M)

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m=map(int,input().split())
A=[]
s=''
for i in range(l):
  s=s+str(a+b*i)
print(int(s)%m)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
AtCoder A
"""

import sys, math, random
import numpy as np

# N = int(input())
# A = list(map(int,input().split())) # N row 1 column
# A = [int(input()) for _ in range(N)] # 1 row N column
# S = str(input()) # str(input()) == input() -> 'abc'
# S = list(input()) # abc -> ['a','b','c']
# S.replace('ABC','X') # "testABCABC" -> "testXX"
 
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
 
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    L,A, B,M = list(map(int,input().split()))
    S=""
    for l in range(L):
        S+=str(A)
        A+=B
    print(int(S)%M)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
L, A, B, M = map(int, input().split())

s = ""
for i in range(L):
  s += str(A + B * i)
print(int(s) % M)

Submission status: Time Limit Exceeded

Solution code:
def inv(x, N):
    def invv(a, n):
        if a == 1: return (1, 0)
        if a == 0: return (-1, -1)
        b, m = a, n
        while m != 0: b,m = m,b%m
        if b > 1: return (-1, -1)
        k = n // a
        y, yy = invv(n % a, a)
        if y < 0: return (-1, -1)
        x = yy - k * y
        while x < 0:
            x += n
            y -= a
        return (x, y)
    return invv(x, N)[0]

L, A, B, M = map(int, input().split())
X = [10**i for i in range(20)]
Y = [max((10**i-A+B-1)//B,0) for i in range(20)]
ans = 0
s = 0
for i in range(19)[::-1]:
    a, b, n = A+B*Y[i], B, max(min(L, Y[i+1])-Y[i], 0)
    a, b = a+b*(n-1), -b
    if n == 0:
        continue
    r = 10**(i+1)
    tmp = (((1-r)*a+b*(1-r**(n-1))*r-(1-r)*(a+(n-1)*b)*r**n)*10**s)//((1-r)**2)
    # tmp = (((1-r)*a+b*(1-pow(r,n-1,M))*r-(1-r)*(a+(n-1)*b)*pow(r,n,M))*pow(10,s,M))*inv((1-r)**2,M)%M
    ans = (ans+tmp)%M
    s += (i+1)*n
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

l, a, b, m = map(int, input().split())
x = ''
for i in range(l):
    x += str(a + b * i)
print(int(x) %m)

Submission status: Time Limit Exceeded

Solution code:
l, a, b, m = list(map(int, input().split()))

print(int(''.join([str(a + b * i) for i in range(0, l)])) % m)

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m = map(int,input().split())
suretsu=[]
suretsu.append(a)
for i in range(l-1):
    s = a+b*(i+1)
    suretsu.append(s)

suji=int("".join(map(str, suretsu)))

print(suji%m)

Submission status: Time Limit Exceeded

Solution code:
def sol():
    l,a,b,m=map(int,input().split())
    d=[]
    x=""
    for i in range(l):
        x+=str(a+i*b)
    print(int(x)%m)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m=map(int,input().split())

s=str()

for i in range(l):
    c=a+b*i
    s=s+str(c)

ac=int(s)

ans=ac % m

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from math import ceil, log10

L, A, B, M = map(int, input().split())

t = ''
if B == 0:
    t = str(A) * L
else:
    for i in range(L):
        c = A + B * i
        t += str(c)

lm = ceil(log10(M))

j = 0

while len(t) > lm + 1:
    t = str(int(t[j:j + lm + 1]) % M) + t[j + lm + 1:]
t = int(t) % M
print(t)

Submission status: Time Limit Exceeded

Solution code:

a = list(map(int, input().split()))
#print(a)
ans=""
for x in range(a[0]):
    num=a[1]+a[2]*x
    ans += str(num)
print(int(ans)%int(a[3]))

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

import math

def modpow(a,n,mod):
    res = 1
    while (n > 0):
        if n & 1:
            res = res * a % mod
        a = a * a % mod
        n >>= 1
    return res

l,a,b,m = na()
k = 0
ans = 0
for i in reversed(range(l)):
    ans = (ans+(a%m+(b%m)*(i%m))*(modpow(10,k,m)))%m
    k = (k+int(math.log10(a+b*i)+1))

print(ans%m)

Submission status: Time Limit Exceeded

Solution code:
def sol():
    l,a,b,m=map(int,input().split())
    d=[]
    for i in range(l):
        d.append(str(a+i*b))
    x="".join(d)
    print(int(x)%m)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = [int(i) for i in input().split()]
list=[]
for i in range(0,int(L)):
    list.append(A+B*i)
list=map(str, list)
a=''.join(list)
print(int(a)%M)

Submission status: Time Limit Exceeded

Solution code:
inp = input().split()
L = int(inp.pop(0))
A = int(inp.pop(0))
B = int(inp.pop(0))
M = int(inp.pop(0))

summ = int(''.join([str(A+B*i) for i in range(L)]))
print(summ%M)

Submission status: Time Limit Exceeded

Solution code:
L, A, B, M = map(int, input().split())

X = [str(A + B * i) for i in range(L)]
print(int("".join(X)) % M)

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m = map(int,input().split())
tlist = []
for i in range(l):
    tlist.append(a+b*i)

str_tlist = [str(i) for i in tlist ]
conbined = "".join(str_tlist)
conbined = int(conbined)
print(conbined%m)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M=map(int,input().split())
S=""
for i in range(L):
    S+=str(A+B*i)
print(int(S)%M)

Submission status: Time Limit Exceeded

Solution code:
from math import ceil, log10

L, A, B, M = map(int, input().split())

t = ''
for i in range(L):
    c = A + B * i
    t += str(c)

lm = ceil(log10(M))

j = 0

while len(t) > lm + 1:
    t = str(int(t[j:j + lm + 1]) % M) + t[j + lm + 1:]
t = int(t) % M
print(t)

Submission status: Time Limit Exceeded

Solution code:
L, A, B, M = input().split()
data = []
for i in range(int(L)):
  d = int(A) + int(B)*i
  data.append(str(d))
suuretsu = "".join(data)
ans = int(suuretsu)%int(M)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = [i for i in input().split()]
list=[]
for i in range(0,int(L)):
    list.append(str(int(A)+int(B)*i))
a=''.join(list)
print(int(a)%int(M))

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m = map(int,input().split())
tlist = []
for i in range(l):
    tlist.append(a+b*i)

str_tlist = [str(i) for i in tlist ]
conbined = ""
for x in str_tlist:
    conbined += x
conbined = int(conbined)
print(conbined%m)

Submission status: Time Limit Exceeded

Solution code:
a, b, c, d = input().split()
l = ''
for i in range(int(a)):
    b = int(b)
    c = int(c)
    l += str(b+c*i)

l = int(l)
print(l%int(d))
'''
b = int(input().split())
c = int(input().split())
d = int(input().split())
'''

Submission status: Time Limit Exceeded

Solution code:
s = [int(x) for x in input().split()]
l, a, b, m = s[0:4]
sl = ""
for x in range(l):
    sl += str(a + b*(x))
    if int(sl) > m:
        sl = str(int(sl) % m)
print(int(sl)%m)

Submission status: Time Limit Exceeded

Solution code:
l, a, b, m = map(int, input().split())

sum_val = ''
for i in range(l):
    tmp = a + (b * i)
    if i == 0 and a == 0:
        sum_val = ''
    else:
        sum_val += str(tmp)

print(int(sum_val) % m)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M=map(int, input().split())
x=''
for n in range(L):
  x=x+str(A+B*n)

print(int(x)%M)

Submission status: Time Limit Exceeded

Solution code:
l, a, b, m = map(int, input().split())

s = ""
for i in range(l):
    s += str(a + b * i)

print(int(s) % m)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = map(int,input().split())

lists = []
for i in range(L):
    lists.append(str(A+B*i))
    
answer = ' '

for x in lists:
    answer += x
    
print(int(answer)%M)

Submission status: Time Limit Exceeded

Solution code:
L, A, B, M = map(int,input().split())
retsu = []
for i in range(L):
    retsu.append(str(A + B * i))
print(int(''.join(retsu)) % M)

Submission status: Time Limit Exceeded

Solution code:
s = [int(x) for x in input().split()]
l, a, b, m = s[0:4]
ll = []
for x in range(l):
    ll.append(str(a + b*(x)))
sl = "".join(ll)
print(int(sl)%m)

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m=map(int,input().split())
c=[a]

for i in range(l):
    c.append(c[i]+b)
c=c[:l]
c=[str(n) for n in c]
c=int(''.join(c))

print(c%m)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,N = map(int,input().split())
res = str(A)
for i in range(L-1):
    A += B
    res += str(A)
print(int(res)%N)

Submission status: Time Limit Exceeded

Solution code:
T = input()
data = T.split()
L, A, B, M = list(map(int, data))
ans_list = []
a = A
for _ in range(L):
    ans_list.append(a)
    a += B 
ans_tmp = int(''.join(map(str, ans_list)) ) 
print(ans_tmp % M)

Submission status: Time Limit Exceeded

Solution code:
list = input().split(' ')

L = int(list[0])
A = int(list[1])
B = int(list[2])
M = int(list[3])

ans = ""
for i in range(L):
    ans += str(A + B * i)
print(int(ans) % M)

Submission status: Time Limit Exceeded

Solution code:
import math
L,A,B,M = map(int, input().split())

d = 0
for i in reversed(range(L)):
  if (d == 0):
    keta = 0
  else:
    keta = int(math.log10(d))+1
  d = (d + 10**keta * (A + B*i))

print(d % M)

Submission status: Time Limit Exceeded

Solution code:
l, a, b, m = map(int, input().split())
s = ""
for i in range(l):
    x = a + b * i
    s += str(x)
print(int(s) % m)

Submission status: Time Limit Exceeded

Solution code:
l, a, b, m = map(int, input().split())

n = str()
for i in range(l):
    n += str(a + b * i)

k = len(n)

L = []
for i in range(k):
    t = 10 ** i
    spl = t % m
    L.append(spl)

N = [int(s) for s in n]

Amari = [q * r for (q, r) in zip(L[::-1], N)]
amari_sum = sum(Amari)

ans = amari_sum % m
print(ans)

Submission status: Time Limit Exceeded

Solution code:
l, a, b, m = map(int,input().split())
num_list = [str(a+x*b) for x in range(l)]
print(int("".join(num_list))%m)

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = map(int,input().split())

st = ""

for i in range(L):
	st = st + str(A + B*i)
	num = int(st)%M
	st = str(num)

print(num)

Submission status: Time Limit Exceeded

Solution code:
(l, a, b, m) = map(int, input().split())


def progression(a, b):
    i = -1
    while 1:
        i += 1
        yield a + b * i


s = ''
for i, p in enumerate(progression(a, b)):
    s += str(p)
    if (i == l - 1):
        break
print(int(s) % m)

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m=map(int,input().split())
s=''.join([str(a+i*b) for i in range(l)])
print(int(s)%m)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
l,a,b,m = map(int,input().split())
x = []
for i in range(l):
    x.append(a+b*i)
a = "".join(map(str,x))
print(np.mod(int(a), m))

Submission status: Time Limit Exceeded

Solution code:
a = [int(i) for i in input().split()]
x  = "".join([str(a[1]+a[2]*i) for i in range(a[0])])
print(int(x)%a[3])

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = map(int,input().split())
ls = []
for i in range(0,L):
    ls.append(A+B*i)
K = "".join([str(n) for n in ls])
K = int(K)
print(K%M)

Submission status: Time Limit Exceeded

Solution code:
a = [int(i) for i in input().split()]
x  = [a[1]+a[2]*i for i in range(a[0])]
x_str = [str(n) for n in x]
s = "".join(x_str)
print(int(s)%a[3])

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = map(int,input().split())
C=[]
for i in range(L):
  c = A + B*i
  C.append(c)
d=""
for j in range(L):
  d = d+ str(C[j])
print(int(d)% M)

Submission status: Time Limit Exceeded

Solution code:
def input_from_console():

    l, a, b, m = map(int, input().split())
    return l, a, b, m


def solve(l, a, b, m):
    number_string = ''
    for i in range(l):
        number_string += str(a + b * i)

    return int(number_string) % m


def main():
    l, a, b, m = input_from_console()
    print(solve(l, a, b, m))


if __name__ == "__main__":
    import sys

    if sys.gettrace():  # Check if the python interpreter is in debug mode or not.
        check_cases()
    else:
        main()

Submission status: Time Limit Exceeded

Solution code:
L,A,B,M = [int(i) for i in input().split()]
b=0
a=0
for i in range(0,L):
    a=A+B*i
    b=str(b)+str(a)
print(int(b)%M)

Submission status: Time Limit Exceeded

Solution code:
l,a,b,m = map(int,input().split())
x = []
for i in range(l):
    x.append(a+b*i)
a = "".join(map(str,x))
print(int(a)%m)

Submission status: Accepted

Solution code:
def rec(r, b, c, a0, n, mod):
    # a_n = r * a_{n-1} + b * n + c
    a = a0
    n_ = 0
    c += b
    diff = 1
    while n:
        n, m = divmod(n, 2)
        if m:
            a = (a * r + b * n_ + c) % mod
            n_ += diff
        r, b, c = r*r%mod, (r*b+b)%mod, (r*c+b*diff+c)%mod
        diff <<= 1
    return a

def main():
    L, A, B, M = map(int, input().split())

    def bis(d):
        # d 桁以上になる最小の項
        n = 10**(d-1)
        ng = -1
        ok = L
        while ng + 1 < ok:
            c = ok+ng >> 1
            s_c = A + B * c
            if s_c >= n:
                ok = c
            else:
                ng = c
        return ok
    Idxs = [0]
    for d in range(1, 19):
        Idxs.append(bis(d))
    Idxs.append(L)

    ans = 0
    for d, (l, r) in enumerate(zip(Idxs, Idxs[1:])):
        if r - l == 0:
            continue
        s_l = A + B * l
        n = r - l
        ratio = 10**d
        a = rec(ratio, B, s_l, s_l, n-1, M)
        #print(d, a)
        ans = (ans * pow(10, d*n, M) + a) % M
    print(ans)

main()

Submission status: Accepted

Solution code:
L,A,B,mod=map(int,input().split())
def f(l):
  return max(0,(10**l-A-1)//B+1)

def m(a,b):
  r=[[0]*len(b[0]) for i in range(len(a))]
  for i in range(len(a)):
    for k in range(len(b)):
      for j in range(len(b[0])):
        r[i][j]=(r[i][j]+a[i][k]*b[k][j])%mod
  return r

def p(a,n):
  r=[[0]*len(a) for i in range(len(a))]
  b=[]
  for i in range(len(a)):
    r[i][i]=1
    b.append(a[i][:])
  l=n
  while l>0:
    if l&1:
      r=m(b,r)
    b=m(b,b)
    l>>=1
  return r

X=[[0,0,1],[0,0,A],[0,0,0]]
Y,R,Z=0,1,0
while L:
  Y=[[1,0,0],[B,1,0],[0,1,pow(10,R,mod)]]
  Z=min(L,f(R)-f(R-1))
  L-=Z
  Y=p(Y,Z)
  X=m(Y,X)
  R+=1
print(X[2][2]%mod)

Submission status: Accepted

Solution code:
L,A,B,mod=map(int,input().split())
def f(l):
  return max(0,(10**l-A-1)//B+1)

def m(a,b):
  r=[[0]*len(b[0]) for i in range(len(a))]
  for i in range(len(a)):
    for k in range(len(b)):
      for j in range(len(b[0])):
        r[i][j]=(r[i][j]+a[i][k]*b[k][j])%mod
  return r

def p(a,n):
  r=[[0]*len(a) for i in range(len(a))]
  b=[]
  for i in range(len(a)):
    r[i][i]=1
    b.append(a[i][:])
  l=n
  while l>0:
    if l&1:
      r=m(b,r)
    b=m(b,b)
    l>>=1
  return r

'''
100   001
B10 * 00s
01l   00P
'''

X=[[0,0,1],[0,0,A],[0,0,0]]
Y,R,Z=0,1,0
while L:
  Y=[[1,0,0],[B,1,0],[0,1,pow(10,R,mod)]]
  Z=min(L,f(R)-f(R-1))
  L-=Z
  Y=p(Y,Z)
  X=m(Y,X)
  R+=1
print(X[2][2]%mod)

Submission status: Accepted

Solution code:
import sys
from math import log10

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 19 + 7
EPS = 10 ** -10

def bisearch_min(mn, mx, func):
    ok = mx
    ng = mn
    while ng+1 < ok:
        mid = (ok+ng) // 2
        if func(mid):
            ok = mid
        else:
            ng = mid
    return ok

def mat_pow(mat, init, K, MOD):
    """ 行列累乗 """

    def mat_dot(A, B, MOD):
        """ 行列の積 """

        if not isinstance(A[0], list) and not isinstance(A[0], tuple):
            A = [A]
        if not isinstance(B[0], list) and not isinstance(A[0], tuple):
            B = [[b] for b in B]
        n1 = len(A)
        n2 = len(A[0])
        _ = len(B)
        m2 = len(B[0])
        res = list2d(n1, m2, 0)
        for i in range(n1):
            for j in range(m2):
                for k in range(n2):
                    res[i][j] += A[i][k] * B[k][j]
                    res[i][j] %= MOD
        return res

    def _mat_pow(mat, k, MOD):
        """ 行列matをk乗する """

        n = len(mat)
        res = list2d(n, n, 0)
        for i in range(n):
            res[i][i] = 1
        while k > 0:
            if k & 1:
                res = mat_dot(res, mat, MOD)
            mat = mat_dot(mat, mat, MOD)
            k >>= 1
        return res

    res = _mat_pow(mat, K, MOD)
    res = mat_dot(res, init, MOD)
    return [a[0] for a in res]

L, a, b, M = MAP()

A = [0] * 20
for i in range(1, 20):
    x = 10 ** i
    # A[i] = bisearch_min(-1, L, lambda m: ceil(x-a, b) <= m)
    A[i] = max(min(ceil(x-a, b), L), 0)
C = [0] * 20
for i in range(1, 20):
    C[i] = A[i] - A[i-1]

init = [0, a, 1]
for d in range(1, 20):
    K = C[d]
    if K == 0:
        continue
    mat = [
        # dp0[i] = dp0[i-1]*10^d + dp1[i-1]*1 + 1*0
        [pow(10, d, M), 1, 0],
        # dp1[i] = dp0[i-1]*0 + dp1[i-1]*1 + 1*b
        [0, 1, b],
        # 1 = dp0[i-1]*0 + dp1[i-1]*0 + 1*1
        [0, 0, 1],
    ]
    res = mat_pow(mat, init, K, M)
    init[0] = res[0]
    init[1] = res[1]
ans = res[0]
print(ans)

# dp0 = [0] * (L+1)
# dp1 = [0] * (L+1)
# dp0[0] = 0
# dp1[0] = a
# for i in range(1, L+1):
#     dp0[i] = (dp0[i-1]*pow(10, int(log10(dp1[i-1]))+1, M) + dp1[i-1]) % M
#     dp1[i] = dp1[i-1] + b
# ans = dp0[-1]
# print(ans)

Submission status: Accepted

Solution code:
import sys
from math import log10

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 19 + 7
EPS = 10 ** -10

def bisearch_min(mn, mx, func):
    ok = mx
    ng = mn
    while ng+1 < ok:
        mid = (ok+ng) // 2
        if func(mid):
            ok = mid
        else:
            ng = mid
    return ok

def mat_pow(mat, init, K, MOD):
    """ 行列累乗 """

    def mat_dot(A, B, MOD):
        """ 行列の積 """

        if not isinstance(A[0], list) and not isinstance(A[0], tuple):
            A = [A]
        if not isinstance(B[0], list) and not isinstance(A[0], tuple):
            B = [[b] for b in B]
        n1 = len(A)
        n2 = len(A[0])
        _ = len(B)
        m2 = len(B[0])
        res = list2d(n1, m2, 0)
        for i in range(n1):
            for j in range(m2):
                for k in range(n2):
                    res[i][j] += A[i][k] * B[k][j]
                    res[i][j] %= MOD
        return res

    def _mat_pow(mat, k, MOD):
        """ 行列matをk乗する """

        n = len(mat)
        res = list2d(n, n, 0)
        for i in range(n):
            res[i][i] = 1
        while k > 0:
            if k & 1:
                res = mat_dot(res, mat, MOD)
            mat = mat_dot(mat, mat, MOD)
            k >>= 1
        return res

    res = _mat_pow(mat, K, MOD)
    res = mat_dot(res, init, MOD)
    return [a[0] for a in res]

L, a, b, M = MAP()

A = [0] * 20
for i in range(1, 20):
    x = 10 ** i
    res = bisearch_min(-1, L, lambda m: ceil(x-a, b) <= m)
    A[i] = res
C = [0] * 20
for i in range(1, 20):
    C[i] = A[i] - A[i-1]

init = [0, a, 1]
for d in range(1, 20):
    K = C[d]
    if K == 0:
        continue
    mat = [
        # dp0[i] = dp0[i-1]*10^d + dp1[i-1]*1 + 1*0
        [pow(10, d, M), 1, 0],
        # dp1[i] = dp0[i-1]*0 + dp1[i-1]*1 + 1*b
        [0, 1, b],
        # 1 = dp0[i-1]*0 + dp1[i-1]*0 + 1*1
        [0, 0, 1],
    ]
    res = mat_pow(mat, init, K, M)
    init[0] = res[0]
    init[1] = res[1]
ans = res[0]
print(ans)

# dp0 = [0] * (L+1)
# dp1 = [0] * (L+1)
# dp0[0] = 0
# dp1[0] = a
# for i in range(1, L+1):
#     dp0[i] = (dp0[i-1]*pow(10, int(log10(dp1[i-1]))+1, M) + dp1[i-1]) % M
#     dp1[i] = dp1[i-1] + b
# ans = dp0[-1]
# print(ans)