Problem:


Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

1 \leq N \leq 2 \times 10^5

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68



Sample input:
4 3
3543


Sample output:
6

Submission status: Accepted

Solution code:
N,P = map(int,input().split())
S = map(int,input())
S_li = [0]*(N+1)
S_rev = reversed(tuple(S))

tmp = 0
count= 0
from  collections import Counter

if 10%P==0:
    counter = 0
    for i,num in enumerate(S_rev):
        if num%P==0:
            counter += N-i
    print(counter)

else:
    ctr = [0] * P
    ctr[0] = 1
    ret = 0
    t = 0
    c = 1
    for x in S_rev:
        t = (t + c * x) % P
        ret += ctr[t]
        ctr[t] += 1
        c = c * 10 % P
 
    print(ret)

Submission status: Accepted

Solution code:
n, mod = map(int, input().split())
S = input()

total = 0
if mod == 2 or mod == 5:
	for i, q in enumerate(S):
		if int(q)%mod == 0:
			total += i+1
else:
	counts = [0]*mod
	counts[0] = 1
	h = 0
	
	d = 1
	for s in reversed(S):
		m = int(s)*d%mod
		h = (h+m)%mod
		total += counts[h]
		counts[h] += 1
		d = (d*10)%mod

print(total)

Submission status: Accepted

Solution code:
def main():
    N, P = map(int, input().split())
    A = map(int, input())

    if 10 % P == 0:
        ret = 0
        for i, x in enumerate(reversed(tuple(A)), start=0):
            if x % P == 0:
                ret += N - i
        print(ret)
        return

    ctr = [0] * P
    ctr[0] = 1

    ret = 0
    t = 0
    c = 1
    for x in reversed(tuple(A)):
        t = (t + c * x) % P
        ret += ctr[t]
        ctr[t] += 1
        c = c * 10 % P

    print(ret)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, P = map(int,input().split())
S = str(input())
L = len(S)
ans = 0
dic = {0:1} #一番右端は0なのでこれは常に必要
now = 0
if P == 2 or P == 5:
  kotae = 0
  for i in range(L):
    if int(S[L-1-i])%P == 0:
      kotae += L-i
  print(kotae)
  exit(0)
else:
  for i in range(L):
    now += int(S[L-1-i])*pow(10,i,P)
    temp = now%P
    if temp not in dic:
      dic[temp] = 1
    else:
      dic[temp] += 1
#print(dic)
ans = 0  
for i in dic.values():
  if i != 1:
    ans += i*(i-1)//2
print(ans)

Submission status: Accepted

Solution code:
n, p = map(int, input().split())
s = input()
if p==2 or p==5:
    ans = 0
    for i in range(n):
        if int(s[i])%p==0:
            ans += i+1
    print(ans)
else:
    di = {0: 1}
    tmp = 0
    for i in range(n):
        tmp += int(s[n-i-1])*pow(10, i, p)
        tmp %= p
        if tmp in di:
            di[tmp] += 1
        else:
            di[tmp] = 1
    ans = 0
    for i in di.values():
        ans += i*(i-1)//2
    print(ans)

Submission status: Accepted

Solution code:
N,P = map(int,input().split())
S = input()

if P in (2,5):
    ans = 0
    for i,c in enumerate(S):
        if int(c)%P==0:
            ans += i+1
    print(ans)
    exit()

mem = [0]
j = 1
for c in S[::-1]:
    mem.append((mem[-1] + int(c)*j) % P)
    j *= 10
    j %= P
from collections import Counter
ctr = Counter(mem)
ans = 0
for v in ctr.values():
    ans += v*(v-1)//2
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,copy
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,p = inpl()
t = list(input())[::-1]
res = 0
if p == 2 or p == 5:
    t = t[::-1]
    for i,x in enumerate(t):
        if int(x) % p == 0:
            res += i+1
    print(res)
    quit()
d = defaultdict(int)
now = 0
d[0] += 1
# print(t)
for i,x in enumerate(t):
    tmp = (pow(10,i,p) * int(x)) % p
    now += tmp
    now %= p
    d[now] += 1
# print(d)
for va in d.values():
    res += va*(va-1)//2
print(res)

Submission status: Accepted

Solution code:
from collections import Counter
n,mod = map(int,input().split())
s = input()
if mod == 2:
    ans = 0
    for i in range(n-1,-1,-1):
        if int(s[i]) % 2 == 0:
            ans += i+1
    print(ans)
    quit()
elif mod == 5:
    ans = 0
    for i in range(n-1,-1,-1):
        if int(s[i]) % 5 == 0:
            ans += i+1
    print(ans)
    quit()

l = [0]*(n+1)
for i in range(n-1,-1,-1):
    l[i] = (l[i+1]+int(s[i])*pow(10,n-1-i,mod))%mod
#print(l)
c = Counter(l)
#print(c)
def nC2(i):
    return i*(i-1)//2
ans = c[0]-1+nC2(c[0]-1)
for i in range(1,mod):
    ans += nC2(c[i])
print(ans)

Submission status: Accepted

Solution code:
import collections
import sys
sys.setrecursionlimit(10 ** 8)

def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    N, P = ZZ()
    S = input()
    output = 0

    if P in {2, 5}:
        for i in range(N):
            if int(S[i])%P == 0: output += i+1
        print(output)
        return

    dp = [0] * (N+1)
    ex = 1
    for i in range(N):
        dp[i+1] = (int(S[-1-i])*ex + dp[i]) % P
        ex *= 10
        ex %= P

    d = collections.defaultdict(int)
    for i in range(N+1): d[dp[i]] += 1

    for i in d.keys(): output += (d[i] * (d[i]-1) // 2)
    print(output)

    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter

N, P = map(int, input().split())
Ss = input()

if P == 2 or P == 5:
    ans = 0
    for i, S in enumerate(Ss):
        if int(S)%P == 0:
            ans += i+1
else:
    As = [0]
    A = 0
    D = 1
    for S in Ss[::-1]:
        S = int(S)
        A = (A + S*D) % P
        As.append(A)
        D = D*10 % P

    cnt = Counter()
    ans = 0
    for A in As:
        ans += cnt[A]
        cnt[A] += 1

print(ans)

Submission status: Accepted

Solution code:
import sys
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()

N,P = map(int,S().split())
S = LI2()

if P == 2 or P == 5:  #10と素でない場合一番右の桁で決まる
    ans = 0
    for i in range(N):
        if S[i] % P == 0:
            ans += i+1
    print(ans)
    exit()

A = [0]  #A[i] = 下i桁をPで割った余り
for i in range(1,N+1):
    A.append((A[i-1]+pow(10,i,P)*S[N-i]) % P)

from collections import Counter

c = Counter(A)
B = c.values()

ans = 0

for i in B:
    ans += (i*(i-1)//2)

print(ans)

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

N,P = map(int,S().split())
S = LI2()

if P == 2 or P == 5:  #10と素でない場合一番右の桁で決まる
    ans = 0
    for i in range(N):
        if S[i] % P == 0:
            ans += i+1
    print(ans)
    exit()

A = [0]  #A[i] = 下i桁をPで割った余り
for i in range(1,N+1):
    A.append((A[i-1]+pow(10,i,P)*S[N-i]) % P)

from collections import Counter

c = Counter(A)
B = c.values()

ans = 0

for i in B:
    ans += (i*(i-1)//2)

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin 
from collections import Counter

N, P = map(int, stdin.readline().split())
S = stdin.readline().strip()

ans = 0
if P in (2, 5):
	for i in range(N):
		if int(S[i]) % P == 0:
			ans += i + 1


else:

	count = Counter()
	ten = 1
	mod = 0
	for i in range(N):
		x = (int(S[N - i - 1])*ten + mod) % P
		ten = ten*10 % P 
		mod = x
		count[x] += 1

	count[0] += 1


	for i in count.values():
		ans += i*(i - 1)//2

print (ans)

Submission status: Accepted

Solution code:

from collections import defaultdict


N,P = map(int, input().split())
S = input()
ans = 0
if P in [2,5]:
    
    for i in range(N):
        if int(S[i]) % P == 0:
            ans += i + 1

else:
    d = defaultdict(int)
    d[0] = 1
    curr = 0
    for i in range(N):
        curr = curr + int(S[N-1-i]) * pow(10, i, P)
        curr %= P
        ans += d[curr]
        d[curr] += 1

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import Counter

def ep(*params):
    print(*params,file=sys.stderr)

(N,P) = list(map(int,input().split()))
S = input().rstrip()

if 10%P == 0:
    ans = 0
    for i in range(N):
        if int(S[i])%P == 0:
            ans += i+1
    print(ans)
    sys.exit()

ans = 0
d = [0]*(N+1)
cnt = [0]*P
ten = 1

for i in range(N-1,-1,-1):
    a = int(S[i]) * ten % P
    d[i] = (d[i+1]+a) % P
    ten *= 10
    ten %= P

#ep(d)

for i in range(N,-1,-1):
    ans += cnt[d[i]]
    cnt[d[i]] += 1;
    #ep(i,ans,cnt)
#ep(cnt)
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

n, p = map(int, input().split())
s = input().rstrip()

total = 0
if p in [2, 5]:
    for i in range(n-1, -1, -1):
        if int(s[i]) % p == 0:
            total += i + 1
else:
    dp = [0] * (n + 1)
    fac = 1
    for i in range(n-1, -1, -1):
        dp[i] = (dp[i + 1] + int(s[i]) * fac) % p
        fac = (fac * 10) % p

    c = Counter(dp)

    for k, v in c.items():
        if v >= 2:
            total += v * (v - 1) // 2

print(total)

Submission status: Accepted

Solution code:
def main():
    N,p = map(int, input().split())
    S = input()
    S = S[::-1]

    if p==2 or p==5:
        ans = 0
        for i,s in enumerate(S):
            if int(s)%p==0:
                ans += N-i
        print(ans)
    else:
        # modpを作成
        modp_counter = [0] * p
        modp = 0
        modp_counter[0] = 1 # 割り切れるやつが入る場所の初期値を1にしておかないと、1つ割り切れるやつがきたときにpair_count+=0となってしまう(pair_count+=1になるべきなのに)
        pair_count = 0
        d = 1
        for s in S:
            modp = (int(s)*d%p+modp)%p
            pair_count += modp_counter[modp]
            modp_counter[modp] += 1
            d *= 10
            d %= p # 計算量削減
        print(pair_count)

main()

Submission status: Accepted

Solution code:
N,P = map(int,input().split())
lst=[int(d) for d in input()]
chk=[0]*P
t=0
c=1
if P==2:
 ans=0 
 a=N
 for x in lst[::-1]:
  if x%2==0:
   ans+=a
  a-=1
 print(ans)
elif P==5:
 ans=0 
 a=N
 for x in lst[::-1]:
  if x%5==0:
   ans+=a
  a-=1  
 print(ans)
else:
 for x in lst[::-1]:
  t+=c*x
  t%=P
  chk[t]+=1
  c*=10
  c%=P 
 md=0
 ans=chk[0]
 d=1
 for i in range(N-1):
  md=(md+lst[N-1-i]*d)%P
  if chk[md]>0:
   chk[md]-=1
  ans+=chk[md]
  d*=10
  d%=P
 print(ans)

Submission status: Accepted

Solution code:
N, P = map(int, input().split())
S = input()

if P == 2 or P == 5:
    def solve25(N, P, S):
        c = 0
        for i in range(N-1, -1, -1):
            if int(S[i]) % P == 0:
                # 以降桁を増やしてもOK
                c += i+1
        return c
    print(solve25(N, P, S))
else:
    def solve(N, P, S):
        rcounts = [0] * P
        rcounts[0] = 1 # sそのものが割り切れた場合に引き算する相手がいないから
        ints = 0
        for i, s in enumerate(S[::-1]):
            ints += int(s) * pow(10, i, P)
            r = ints % P
            rcounts[r] += 1
        c = 0
        for v in rcounts:
            c += v*(v-1)//2
        return c
    print(solve(N, P, S))

Submission status: Accepted

Solution code:
from collections import Counter
N, P = map(int, input().split())
S = list(map(int, list(input())))
ans = 0
if P in (2, 5):
    cnt = 0
    for i, s in enumerate(S):
        if s % P == 0:
            ans += i+1
else:
    S.reverse()
    now = 0
    d = [0] * (N+1)
    for i in range(N):
        now += S[i] * pow(10, i, P)
        now %= P
        d[i] = now % P
    c = Counter(d)
    for i, v in c.items():
        ans += v*(v-1)//2
    #print(d)

print(ans)

Submission status: Accepted

Solution code:
N,P=map(int,input().split())
S=input()

if 10%P==0:
    ans=0
    for i in range(N):
        if int(S[i])%P==0:
            ans+=(i+1)
    print(ans)
else:
    S=S[::-1]
    D={}
    D[0]=1
    Amari=0
    for i in range(N):
        I=((Amari)+(pow(10,i,P)*int(S[i])))%P
        Amari=I
        if I not in D:
            D[I]=1
        else:
            D[I]+=1
    ans=0
    for k,v in D.items():
        ans+=v*(v-1)//2
    print(ans)
    #print(D)

Submission status: Accepted

Solution code:





N,P = map(int, input().split())
S = input()


"""
たとえばSが 123456789 だとすると
3456 = (3456789 - 789) // 1000
と表せる。
これがPで割り切れる場合、基本的には 3456789 と 789 がPで割り切れるとよい。
これはPと 10**x が互いに素の場合。
なので、10**x とPが互いに素の場合は、
・S[l:]をPで割った時余りがXXXになるものが何個、という情報を、Sの右端から集めていく。ただし、
・あるindexのlのS[l:]を見ているときに、その部分をPで割って余りがKになるなら、そのlに対してlより右にあるrについて、
　S[r:]をPで割った余りがKになるようにrを選んでS[l:r]を作ると、Pで割り切れる数字が得られる。その時点でのmod P = Kの個数に対応する。
　ただし、rに何も選ばない場合（lから端までを数字にする場合）もあるので、これも考慮に入れる。

Pが10と互いに素でない場合は、2と5がありうる。
これについて、それぞれ末尾が2の倍数か5の倍数であれば割り切れるので、
Sを左から見ていって、その数字が見つかれば、そのindexをふくむ左の位置で数字を作ればPで割れる数字ができる
"""

ans = 0
if P in [2, 5]:
    for i in range(N):
        if int(S[i]) % P == 0:
            ans += i+1

else:
    mod_P = [0] * P
    mod_P[0] += 1
    
    # Sを右端から何個かまで見てできる数字をPで割ってできる余り。
    # 数字のまま持っておいて、都度mod P をとるとTLEになるので。
    # 3543 で　3543 % P = (3000 + 543) % P のような感じで右から左にSを見ていく
    curr = 0
    for i in range(N):
        curr = curr + int(S[N-1-i]) * pow(10, i, P)
        curr %= P
        ans += mod_P[curr]
        mod_P[curr] += 1

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

n, p = list(map(int, input().split()))

s = input()


a = 0
t = list(map(int, list(s)))
t.reverse()


if p == 2:
    for i in range(n):
        if t[i] % 2 == 0:
            a += len(t) - i 
elif p == 5:
    for i in range(n):
        if t[i] % 5 == 0:
            a += len(t) - i 

else:
    u = []
    k = 1
    l = 0
    for i in t:
        l = (l + i*k) % p
        u.append(l)
        k = k * 10 % p

    c = Counter(u)
    a += c[0]
    for i in c.values():
        if i > 1:
            a += i * (i-1) // 2


print(a)

Submission status: Accepted

Solution code:
n,p=map(int,input().split())
s=input()
if p==2 or p==5:
    ans=0
    for i in range(n):
        if int(s[i])%p==0:
            ans+=i+1
    print(ans)
else:
    t=[]
    ti=0
    for i in range(n):
        ti+=int(s[-i-1])*pow(10,i,p)
        ti%=p
        t.append(ti)
    from collections import Counter
    tc=Counter(t)
    ans=0
    for v in tc.values():
        ans+=(v*(v-1))//2
    if 0 in tc:
        ans+=tc[0]
    print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    from collections import defaultdict
    N, P = map(int, input().split())
    S = input().rstrip()
    if P in (2, 5):
        ans = 0
        for i, c in enumerate(S):
            if int(c) % P == 0:
                ans += i + 1
        print(ans)
        sys.exit()
    num = 0
    d = 1
    counter = defaultdict(int)
    counter[0] += 1
    for c in S[::-1]:
        num += int(c) * d
        num %= P
        counter[num] += 1
        d *= 10
        d %= P
    ans = 0
    for v in counter.values():
        ans += (v * (v-1)) // 2
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, p = map(int, input().split())
s = input()
sum_cnt = 0
if p in {2, 5}:
    for r in range(n):
        if int(s[r]) % p == 0:
            sum_cnt += (r + 1)
else:
    modp_cnt = [0] * p
    modp_cnt[0] = 1
    subs_modp, pow = 0, 1
    for si in s[::-1]:
        subs_modp += ((int(si)*pow) % p)
        subs_modp %= p
        modp_cnt[subs_modp] += 1
        pow = (pow * 10) % p
        
    for cnt in modp_cnt:
        sum_cnt += cnt * (cnt - 1) // 2
print(sum_cnt)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict
from itertools import combinations, permutations, combinations_with_replacement
from itertools import accumulate
from math import ceil, sqrt, pi

MOD = 10 ** 9 + 7
SIZE = 10 ** 6

N, P = map(int, input().split())
S = input()

answer = 0
if P == 2 or P == 5:
    for i, s in enumerate(S):
        if int(s) % P == 0:
            answer += i + 1
else:
    S = S[::-1]
    cnt = defaultdict(int)
    tmp = 0
    for i, s in enumerate(S):
        tmp += int(s) * pow(10, i, P)
        if tmp % P == 0:
            answer += 1
        answer += cnt[tmp % P]
        cnt[tmp % P] += 1

print(answer)

Submission status: Accepted

Solution code:
from collections import defaultdict
N,p = map(int,input().split())

S = input()[::-1]

d = {}

ans = 0
if p == 2:
    for i in range(N):
        if S[i] in ['0','2','4','6','8']:
            ans += N-i
elif p==5:
    for i in range(N):
        if S[i] in ['0','5']:
            ans += N-i
else:
    d = defaultdict(lambda:0)
    n = 0
    for i in range(N):
        n += pow(10,i,p)*int(S[i])
        n %= p
        d[n] += 1
    ans += d[0]
    for k in d:
        ans += d[k]*(d[k]-1)//2
print(ans)

Submission status: Accepted

Solution code:
import sys
import math
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
from collections import deque
from bisect import bisect_left
from itertools import product
def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def LSI(): return list(map(int, list(sys.stdin.readline().rstrip())))
def LSI2(N): return [list(map(int, list(sys.stdin.readline().rstrip()))) for i in range(N)]
def S(): return sys.stdin.readline().rstrip()
def LS(): return sys.stdin.readline().split()
def LS2(N): return [sys.stdin.readline().split() for i in range(N)]
def FILL(i,h): return [i for j in range(h)]
def FILL2(i,h,w): return [FILL(i,w) for j in range(h)]
def FILL3(i,h,w,d): return [FILL2(i,w,d) for j in range(h)]
def FILL4(i,h,w,d,d2): return [FILL3(i,w,d,d2) for j in range(h)]
def sisha(num,digit): return Decimal(str(num)).quantize(Decimal(digit),rounding=ROUND_HALF_UP)
#'0.01'や'1E1'などで指定、整数に戻すならintをかます
MOD = 998244353
INF = float("inf")
sys.setrecursionlimit(10**6+10)
input = sys.stdin.readline

N,P = MI()
S = S()
mod = 0
ans = 0
dic = {0:1}
if P == 2 or P == 5:
    for i in range(N):
        if int(S[i])%P==0:
            ans += i+1
else:
    for i in range(N-1,-1,-1):
        mod = (mod+pow(10,(N-1-i),P)*int(S[i]))%P
        dic[mod] = dic.get(mod,0)+1
    for i in dic.values():
        ans += int(i*(i-1)/2)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict
N,P=map(int, sys.stdin.readline().split())
S=sys.stdin.readline().strip()

if P in (2,5):
    ans=0
    for i,x in enumerate(S):
        if int(x)%P==0:
            ans+=i+1
    print ans
else:
    L=[int(S)%P]
    for i,x in enumerate(S):
        L.append((L[-1]-int(x)*pow(10,N-1-i,P))%P)
    ans=0
    D=defaultdict(lambda: 0)
    for i in range(N,-1,-1):
        x=L[i]
        ans+=D[x]
        D[x]+=1
    print ans

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict
N,P=map(int, sys.stdin.readline().split())
S=sys.stdin.readline().strip()

if P in (2,5):
    ans=0
    for i,x in enumerate(S):
        if int(x)%P==0:
            ans+=i+1
    print ans
else:
    S=S[::-1]   #文字列Sの右側から累積和を取りたいので、左から数えられるように文字列を反転させる
    L=[0]
    for i,x in enumerate(S):
        x=int(x)
        L.append( (L[-1]+x*pow(10,i,P))%P ) #元の文字列Sの右側から累積和を取った配列を作成
    ans=0
    D=defaultdict(lambda: 0)
    for i in range(N,-1,-1):
        x=L[i]
        ans+=D[x]
        D[x]+=1
    print ans

Submission status: Accepted

Solution code:




from collections import defaultdict


N,P = map(int, input().split())
S = input()

"""
S[l:r]  : (S[l:] - S[r:]) / 10**x

Pが2,5以外であれば、S[l:]とS[r:]がPで割り切れればよい
2,5は10**xと互いに素ではないので例外。

例２の 2020について、左から4つ目の0に着目すると、
0
20
020
2020
いずれも2で割り切れるので、右端にくるものが２で割り切れるだけでよい。
"""

ans = 0

if P in [2,5]:
    for i in range(N):
        if int(S[i]) % P == 0:
            ans += i+1


else:
    mod_P = defaultdict(int)
    mod_P[0] += 1 # S[r:]が空文字になるばあいのやつ
    tmp = 0

    for i in range(N):
        tmp = int(S[N-1-i]) * pow(10, i, P) + tmp
        tmp %= P
        ans += mod_P[tmp]
        mod_P[tmp] += 1


print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
input = lambda:sys.stdin.readline().rstrip()
from collections import Counter
def resolve():
    n, p = map(int, input().split())
    S = input()

    if p == 2 or p == 5:
        res = 0
        for i, c in enumerate(S, 1):
            if int(c) % p == 0:
                res += i
        print(res)
        return

    res = 0
    now = 0
    counter = Counter()
    counter[0] = 1
    for i in range(n):
        now = (10 * now + int(S[i])) % p
        k = now * pow(10, (p - 2) * i, p) % p
        res += counter[k]
        counter[k] += 1
    print(res)
resolve()

Submission status: Accepted

Solution code:
from collections import Counter

N, P = list(map(int, input().split()))
S = input()

ans = 0

if not 10 % P:
    for r in range(N):
        if not int(S[r]) % P:
            ans += r+1
else:
    S = S[::-1]
    s = 0
    d = [0] * (N+1)
    
    for i in range(N):
        s = (s + int(S[i]) * pow(10, i, P)) % P
        d[i+1] = s

    c = Counter()
    for i in range(N+1):
        ans += c[d[i]]
        c[d[i]] += 1
              
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
input = lambda:sys.stdin.readline().rstrip()
from collections import Counter
def resolve():
    n, p = map(int, input().split())
    S = input()

    if p == 2 or p == 5:
        res = 0
        for i, c in enumerate(S, 1):
            if int(c) % p == 0:
                res += i
        print(res)
        return

    res = 0
    now = 0
    counter = Counter()
    counter[0] = 1
    for i in range(n - 1, -1, -1):
        now = (now + pow(10, n - i - 1, p) * int(S[i])) % p
        res += counter[now]
        counter[now] += 1
    print(res)
resolve()

Submission status: Accepted

Solution code:
N, P = map(int, input().split())

S = input()

ans = 0
if P == 2 or P == 5:
    for i, s in enumerate(S):
        if int(s) % P == 0:
            ans += i + 1
else:
    counts = [0] * P
    h = 0
    d = 1
    for s in reversed(S):
        m = int(s) * d % P
        h = (h + m) % P
        counts[h] += 1
        d = (d * 10) % P
        ans = counts[0]
    for i in counts:
        ans += (i*(i-1))//2

print(ans)

Submission status: Accepted

Solution code:
n, p = map(int, input().split())

if p == 2:
    s = input()
    ans = 0
    for i in range(n):
        if int(s[i]) % 2 == 0:
            ans += i + 1
    print(ans)

elif p == 5:
    s = input()
    ans = 0
    for i in range(n):
        if int(s[i]) % 5 == 0:
            ans += i + 1
    print(ans)

else:
    s = input()[::-1]
    mod = 0
    c = [0] * p
    c[0] = 1
    ten = 1
    for i in s:
        mod = (mod + ten * int(i)) % p
        ten = ten * 10 % p
        c[mod] += 1

    ans = 0
    for i in c:
        ans += i * (i - 1) // 2
    print(ans)

Submission status: Accepted

Solution code:
N, P = map(int, input().split())
S = input()

cnt = 0
if P == 2 or P == 5:
    for i in range(N):
        if int(S[i]) % P == 0:
            cnt += (i+1)
            
else:
    dic = dict()
    dic[0] = 1
    r = 0
    for i in range(N):
        s = (pow(10,i,P)*int(S[N-1-i]) + r) % P
        r = s
        if not s in dic:
            dic[s] = 1
        else:
            dic[s] += 1
    for i in dic:
        cnt += dic[i]*(dic[i]-1)/2
        
print(int(cnt))

Submission status: Accepted

Solution code:
n, p = map(int, input().split())
s = input()
a = []
c = 0
if p == 2:
    b = [0]*n
    for i in range(n):
        if int(s[i])%2 == 0:
            b[i] += 1
    for i in range(n):
        if b[i] == 1:
            c += i+1
elif p == 5:
    b = [0]*n
    for i in range(n):
        if int(s[i])%5 == 0:
            b[i] += 1
    for i in range(n):
        if b[i] == 1:
            c += i+1
else:
    b = [0]*p
    b[0] = 1
    d = [1]
    a.append(int(s[-1])%p)
    for i in range(n-1):
        d.append(d[-1]*10%p)
    for i in range(1, n):
        a.append((int(s[-i-1])*d[i]+a[i-1])%p)
    for i in range(n):
        b[a[i]] += 1
    for i in range(p):
        c += int(b[i]*(b[i]-1)/2)
print(c)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
from collections import defaultdict

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# MODの管理をして右から進める
N, P = lr()
S = sr()
dic = defaultdict(int)
dic[0] = 1
num = 0
power = 1
answer = 0
if P%2 == 0 or P%5 == 0:
    x = [i for i, y in enumerate(S, 1) if int(y) % P == 0]
    answer = sum(x)
else:
    for s in S[::-1]:
        s = int(s)
        num += s * power
        num %= P
        answer += dic[num]
        dic[num] += 1
        power *= 10; power %= P

print(answer)
# 14

Submission status: Accepted

Solution code:
import math
import fractions
#import sys
#input = sys.stdin.readline

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

#a = list(map(int, input().split()))

#################################################
#################################################
#################################################
#################################################



n,p = list(map(int, input().split()))
s = input()
nums = []
numsinv = []

for i in range(n):
    nums.append(int(s[i]))
    numsinv.append(int(s[n-1-i]))
    
if(p==2):
    ans = 0
    for i in range(n):
        ans += (numsinv[i]+1)%2 * (n-i)
    print(ans)
    exit()
if(p==5):
    ans=0
    for i in range(n):
        if(numsinv[i]%5==0):
            ans += (n-i)
    print(ans)
    exit()


pows = [0 for i in range(n)]


pows[0] = 1

for i in range(n-1):
    pows[i+1] = (pows[i] * 10)%p

rights = [0]
now = 0
for i in range(n):
    rights.append((rights[-1] + numsinv[i] * pows[i])%p)

lefts = [0]
for i in range(n):
    lefts.append((lefts[-1] + nums[i] * pows[n-1-i])%p)

#print(lefts,rights)

total = lefts[-1]

timesL = [0 for i in range(p)]
timesR = [0 for i in range(p)]

for i in range(n+1):
    timesL[lefts[i]] += 1
    timesR[rights[i]] += 1
    
ans = 0

for i in range(p):
    ans += timesL[i] * timesR[(total-i+p)%p]
#print(timesL,timesR)
print((ans - (n+1))//2)

Submission status: Accepted

Solution code:
N, P = map(int, input().split())
S = input()

S = S[::-1]
result = 0
if P == 2 or P == 5:
    for i in range(N):
        if int(S[i]) % P == 0:
            result += N - i
else:
    t = [0] * P
    m = 1
    n = 0
    for i in range(len(S)):
        t[n] += 1
        n += int(S[i]) * m
        n %= P
        result += t[n]
        m *= 10
        m %= P
print(result)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math

    #inf = 10**17
    #mod = 10**9 + 7

    s,p = map(int, input().split())
    n = input().rstrip()
    n = n[::-1]

    if p == 2 or p == 5:
        res = 0
        for i in range(s):
            a = int(n[i])
            if a%p == 0:
                res += s-i
        print(res)
    else:
        res = [0]*p
        res[0] += 1
        b = 1
        c = 0
        for i in range(s):
            a = int(n[i])
            c += a*b
            c %= p
            res[c] += 1
            b = b*10%p
        ans = 0
        for i in res:
            if i>=2:
                ans += i*(i-1)//2
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,P=map(int,input().split())
S=input()
if P==2 or P==5:
    x=0
    for j in range(N):
        if int(S[j])%P==0:
            x+=j+1
    print(x)
else:
    A=[0]*P
    a=0
    b=1
    for i in range(N):
        a=(a+int(S[(N-1-i)])*b)%P
        A[a]+=1
        b=(b*10)%P
    x=A[0]
    for k in range(P):
        x+=int(A[k]*(A[k]-1)/2)
    print(x)