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:
def main():
    _, P = (int(i) for i in input().split())
    S = [int(s) for s in input()]
    ans = 0
    if P == 2:
        for i, v in enumerate(S, start=1):
            if v % 2 == 0:
                ans += i
    elif P == 5:
        for i, v in enumerate(S, start=1):
            if v == 0 or v == 5:
                ans += i
    else:
        cnt = [0]*P
        d = 1
        pre = 0
        cnt[pre] += 1
        for v in S[::-1]:
            v *= d
            v += pre
            v %= P
            cnt[v] += 1
            d *= 10
            d %= P
            pre = v

        ans = sum(cnt[i]*(cnt[i]-1)//2 for i in range(P))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, P = map(int, input().split())
S = [int(i) for i in input()]
from collections import Counter
def solve(S,N,P):
    if P==2 or P==5:
        ans = 0
        for i in range(N):
            if S[i]%P==0:
                ans += i+1
        return ans
    cum = [0]*(N+1)
    mods = [0]*N
    mods[0] = 1
    for i in range(1,N):
        mods[i] = mods[i-1]*10%P
    for i in range(N):
        cum[i+1] = (cum[i]+S[N-1-i]*mods[i])%P
    c = Counter(cum)
    ans = 0
    for v in c.values():
        ans += v*(v-1)//2
    return ans
print(solve(S,N,P))

Submission status: Accepted

Solution code:
N, P = map(int, input().split())
S = input()
total = 0
if P == 2:
  for idx, right_value in enumerate(S, 1):
    if int(int(right_value)%2==0):
      total += idx
elif P == 5:
  valid_options = (0, 5)
  for idx, right_value in enumerate(S, 1):
    if int(int(right_value) in valid_options):
      total += idx
else:
  histo_modsuffix = [0]*P
  previous = 0
  for i, val in enumerate(reversed(S)):
    scale = pow(10, i, P)
    new_val = (previous + scale*int(val))%P
    histo_modsuffix[new_val] += 1
    previous = new_val
  for val in histo_modsuffix:
    total += val*(val-1)//2
  total += histo_modsuffix[0] # when right hand side is at far end
print(total)

Submission status: Accepted

Solution code:

from collections import defaultdict

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:
    ctr = defaultdict(int)
    ctr[0] = 1
    cur = 0
    for i in reversed(range(N)):
        cur = (cur + int(S[i]) * pow(10, N - i - 1, P)) % P
        ctr[cur] += 1

    ans = 0
    for v in ctr.values():
        ans += v * (v - 1) // 2
    print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq

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

ans = 0

if p == 2 or p == 5:
    for i in range(n):
        a = int(s[n-1-i])
        if a % p == 0: ans += n-i

else:
    d = {0: 1}
    c = 0
    for i in range(n):
        c += (pow(10, i, p)*int(s[n-1-i])) % p
        c %= p
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1

    for dd in d.values():
        ans += dd*(dd-1)//2

print(ans)

Submission status: Accepted

Solution code:
N,P = map(int,input().split())
S= list(map(int, list(input())))[::-1]
counter = [0]*P
counter[0] = 1
ans = 0
sum = 0
d = 0
r = []
mod = 0

if P != 2 and P != 5:
    mod = 1%P
    for i in range(N):
        d = S[i]*mod
        sum = (sum+d)%P
        mod = (mod*10)%P
        counter[sum] += 1
    for k in range(P):
        ans += (counter[k] * (counter[k]-1)) // 2

if P == 2 or P == 5:
    if P == 2:
        r = [0,2,4,6,8]
    if P == 5:
        r = [0,5]
    for j in range(N):
        if S[j] in r: ans += N - j

print(ans)

Submission status: Accepted

Solution code:
n, p = map(int, input().split())
s = list(input())
r = [0] * p
ans = 0
if not (p == 2 or p == 5):
    x, t = 0, 1
    for i in range(-1, -(n + 1), -1):
        x += (int(s[i]) * t)
        x %= p
        r[x] += 1
        t *= 10
        t %= p
    for i in r:
        if i >= 2:
            ans += (i * (i - 1) // 2)
    ans += r[0]
else:
    for i in range(n):
        if int(s[i]) % p == 0:
            ans += (i + 1)
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict


def main():
    N, P = list(map(int, input().split()))
    S = input()
    if P in [2, 5]:
        ans = 0
        # P = 2, 5の時は一番下の位の数だけ見ればカウント可能
        for right in range(N - 1, - 1, - 1):
            if int(S[right]) % P == 0:
                ans += right + 1
        print(ans)
        return
    # 例：S = 3543, P = 3
    # 左からn番目 ～ 1番右の数のmod Pの値を計算
    #     C = [3543, 543, 43, 3] % P = [0, 0, 1, 0]
    # C[m] == C[n] なる m < nのペア数 + C[n] == 0なるnの個数を求める
    #     3 + 3 = 6
    cur_c = 0
    C = [0] * N
    pw = 1
    for n, s in enumerate(S[::-1]):
        cur_c = (cur_c + pw * int(s)) % P
        C[N - 1 - n] = cur_c
        pw = (pw * 10) % P
    counter = defaultdict(int)
    for c in C:
        counter[c] += 1
    ans = 0
    for c in C:
        counter[c] -= 1
        ans += counter[c]
    ans += len([c for c in C if c == 0])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import groupby
n,p=map(int,input().split())
s=[int(i) for i in input()]
if p==2 or p==5:
    ans=0
    for i in range(n-1,-1,-1):
        #Rとなるもの
        if s[i]%p==0:
            ans+=(i+1)
    exit(print(ans))
S=[0]*(n+1)
po=[1]*(n+1)
for i in range(n):
    po[i+1]=po[i]*10
    po[i+1]%=p
for i in range(n-1,-1,-1):
    S[i]=S[i+1]+s[i]*po[n-1-i]
    S[i]%=p
t=[[S[i],i] for i in range(n+1)]
t.sort()
#[L,R)となるのの候補
u=[[i[1] for i in sorted(list(group))] for key,group in groupby(t,key=lambda x: x[0])]
ans=0
for v in u:
    ans+=(len(v))*(len(v)-1)//2
print(ans)

Submission status: Accepted

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

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

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

amari=[0]*P
amari[0]=1

mod=0
for i in range(1,N+1):
  mod=(mod+int(S[-i])*pow(10,i-1,P))%P
  amari[mod]+=1
ans=0
for tmp in amari:
  ans+=tmp*(tmp-1)//2
  
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter
n,p = map(int,input().split())
S = input()
dp = [0]
mod = p
if p==2:
    ans =0
    for i in reversed(range(n)):
        if int(S[i])%2==0:
            ans += i+1
    print(ans);exit()
elif p==5:
    ans =0
    for i in reversed(range(n)):
        if int(S[i])%5==0:
            ans += i+1
    print(ans);exit()
for i in reversed(range(n)):
    dp.append(dp[-1]%mod + pow(10,n-1-i,mod)*int(S[i]))
    dp[-1]%=mod
count = Counter(dp)
ans = 0
for key,val in count.items():
    if val>=2:
        ans += val*(val-1)//2
print(ans)

Submission status: Accepted

Solution code:
"""
タグ：区間
"""
import sys
input = sys.stdin.readline
N, P = map(int, input().split())
S = input().strip()

if P == 5:
    res = 0
    i = 0
    for s in reversed(S):
        if int(s)%5==0:
            res += N-i
        i += 1
    print(res)
elif P == 2:
    res = 0
    i = 0
    for s in reversed(S):
        if int(s)%2==0:
            res += N-i
        i += 1
    print(res)
else:
    T = [0]
    p = 1
    for s in reversed(S):
        T.append(int(s)*p + T[-1])
        p = p*10%P

    cnt = [0]*P
    for i in range(N+1):
        cnt[T[i]%P] += 1

    res = 0
    for c in cnt:
        res += c*(c-1)//2
    print(res)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from math import gcd
from collections import defaultdict

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

answer = 0
if P == 2 or P == 5: # Case when only last digit matters
    for j in range(N - 1, -1, -1): # Enumerate right endpoint
        if S[j] % P == 0:
            answer += j + 1
else: 
    # Enuerate left endpoint from right to left
    # Find number of right endpoints that make the substr % P == 0
    cnts = defaultdict(int)
    suffix = 0
    base = 1
    for i in range(N - 1, -1, -1):
        suffix = (suffix + S[i] * base) % P
        answer += cnts[suffix]  # Substr with length >= 2
        answer += 1 if suffix == 0 else 0 # Substr with length = 1
        cnts[suffix] += 1
        base = base * 10 % P

print(answer)

Submission status: Accepted

Solution code:
from math import gcd
from collections import defaultdict

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

answer = 0
if P == 2 or P == 5:
    for j in range(N - 1, -1, -1): # enumerate right endpoint
        if S[j] % P == 0:
            answer += j + 1
else:
    cnts = defaultdict(int)
    suffix = 0
    base = 1
    for i in range(N - 1, -1, -1):
        suffix = (suffix + S[i] * base) % P
        answer += cnts[suffix]  # Substr with length >= 2
        answer += 1 if suffix == 0 else 0 # Substr with length = 1
        cnts[suffix] += 1
        base = base * 10 % P

print(answer)

Submission status: Accepted

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

if P == 2:
    ans = 0
    for i, d in enumerate(map(int, S)):
        if d % 2 == 0:
            ans += i+1
    print(ans)
elif P == 5:
    ans = 0
    for i, d in enumerate(map(int, S)):
        if d % 5 == 0:
            ans += i+1
    print(ans)
else:
    mods = [0] * P
    mods[0] = 1
    cur_mod = 0
    for i, digit in enumerate(map(int, S)):
        cur_mod += pow(10, N-i-1, P) * digit
        cur_mod %= P
        mods[cur_mod] += 1

    ans = 0
    for count in mods:
        ans += count * (count - 1) // 2

    print(ans)

Submission status: Accepted

Solution code:
N,P = map(int,input().split())
S = list(map(int,list(input())))
if P==2:
    cnt = 0
    for i in range(N):
        if S[i]%2==0:
            cnt += i+1
elif P==5:
    cnt = 0
    for i in range(N):
        if S[i]==0 or S[i]==5:
            cnt += i+1
else:
    A = [0 for _ in range(N)]
    a = 0
    b = 1
    for i in range(N-1,-1,-1):
        a = (a+b*S[i])%P
        A[i] = a
        b = (b*10)%P
    C = {i:0 for i in range(P)}
    for i in range(N):
        C[A[i]] += 1
    cnt = 0
    for i in range(P):
        cnt += (C[i]*(C[i]-1))//2
    cnt += C[0]
print(cnt)

Submission status: Accepted

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

if P == 2:
    ans = 0
    for i in range(N):
        if int(S[i])%2 == 0:
            ans += i+1
elif P == 5:
    ans = 0
    for i in range(N):
        if S[i] == "0" or S[i] == "5":
            ans += i+1
else:
    L = [0]*P
    num = 0
    for i in range(N):
        num += int(S[N-i-1])*pow(10, i, P)
        num %= P
        L[num] += 1
    ans = L[0]
    for i in range(P):
        ans += L[i]*(L[i]-1)//2

print(ans)

Submission status: Accepted

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

if p==2 or p==5:
  ans=0
  for i,ss in enumerate(s):
    if int(ss)%p==0:
      ans+=i+1
  print(ans)
  exit(0)
from collections import Counter
c=Counter()
m=0
c[m]+=1
d=1
s=s[::-1]
for i in range(n):
  m+=int(s[i])*d
  m%=p
  d*=10
  d%=p
  c[m]+=1
ans=0
for v in c.values():
  ans+=v*(v-1)//2
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

s = list(input().strip())

if p == 2 or p == 5:
    ans = 0
    while s:
        if p == 2 and int(s.pop()) % 2 == 0 or p == 5 and int(s.pop()) % 5 == 0:
            ans += n
        n -= 1
    print(ans)
    exit()

a = [0] * p

i = 1
k = 0
while s:
    k = (k + int(s.pop()) * i) % p
    a[k] += 1
    i *= 10
    i %= p

ans = a[0]
for i in a:
    if i >= 2:
        ans += i * (i - 1) // 2
print(ans)

Submission status: Accepted

Solution code:
n,p=map(int,input().split())
s=input()
total=[0]*p#pで割った余りで分類
total[0]=1#t[0]=0の分をあらかじめカウント
t=[0]*(n+1)#s[i:n]を格納する用の配列
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:
    for i in range(n-1,-1,-1):
        t[i]=t[i+1]%p+int(s[i])*pow(10,n-1-i,p)#s[i:n]を漸化式で付け加えていく
        total[t[i]%p]+=1
    ans=0
    for i in range(p):
        ans+=total[i]*(total[i]-1)//2
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n,p=map(int,input().split())
s=input()
ans=0

if p == 2 or p == 5:
  for i in range(n):
    if int(s[i]) % p == 0:
        ans += i + 1
  print(ans)
  exit()
    
total=[0]*p#pで割った余りで分類
total[0]=1#t[0]=0の分をあらかじめカウント
t=[0]*(n+1)#s[i:n]を格納する用の配列
for i in range(n-1,-1,-1):
    t[i]=t[i+1]+int(s[i])*pow(10,n-1-i,p)#s[i:n]を漸化式で付け加えていく
    total[t[i]%p]+=1
    
for i in range(p):
    ans+=total[i]*(total[i]-1)//2
print(ans)

Submission status: Accepted

Solution code:
import collections, sys
N, P = map(int, input().split())
S = input()
s_mod = [0]*(N+1)

ans = 0
if P == 2:
    for i in range(N):
        ans += ((int(S[-(i+1)])%2) ^ 1) * (N-i)
    print(ans)
    sys.exit()
elif P == 5:
    for i in range(N):
        ans += ((int(S[-(i + 1)]) % 5) == 0) * (N - i)
    print(ans)
    sys.exit()


for i in range(N):
    s_mod[i+1] = (pow(10, i, P) * int(S[-(i+1)])+s_mod[i]) % P
c = collections.Counter(s_mod)
for v in c.values():
    ans = (ans + v*(v-1)//2)
print(ans)

Submission status: Accepted

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

c = [0 for i in range(p)]
c[0] = 1
x = 0
ans = 0
for i,j in enumerate(s[::-1]):
  if p == 2 or p == 5:
    if int(j)%p == 0:
      ans += n-i
  x = (x + int(j)*pow(10,i,p))%p
  c[x] += 1
if ans:
  print (ans)
  exit()
for i in range(p):
  ans += (c[i]*(c[i]-1))//2
print (ans)

Submission status: Accepted

Solution code:
from math import factorial
import collections

def permutations_count(n, r):
    ''' 順列 '''
    return factorial(n) // factorial(n - r)


def combinations_count(n, r):
    ''' 組み合わせ '''
    return factorial(n) // (factorial(n - r) * factorial(r))


n,p = map(int, input().split())
S = input()
su = 0

if p > 6 or p == 3:

    lis = []
    amari = 1
    lis.append(int(S[-1]) % p)

    for i in range(2, len(S)+1):
        amari = (amari * 10) % p
        lis.append((int(S[-1*i]) * amari + lis[i-2]) % p)

    c = collections.Counter(lis)

    for k in c:
        if c[k] > 1:
            su += combinations_count(c[k], 2)

    su += c[0]

    print(su)

else:
    S = S[::-1]
    for i in range(len(S)):
        if int(S[i]) % p == 0:
            su += len(S)-i
    print(su)

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):
    s = int(s)
    if s % P == 0:
      ans += i+1
else:
  mods = [0] * (N+1)
  for i in range(N-1, -1, -1):
    mods[i] = (int(S[i])*pow(10, N-i-1, P)+mods[i+1]) % P
  c = dict()
  for m in mods:
    c[m] = c.get(m, 0)+1
  for key in c:
    ans += c[key]*(c[key]-1)//2

print(ans)

Submission status: Accepted

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

mods = [0] * (N+1)
for i in range(N-1, -1, -1):
  mods[i] = (int(S[i])*pow(10, N-i-1, P)+mods[i+1]) % P
c = dict()
for m in mods:
  c[m] = c.get(m, 0)+1

ans = 0
if P == 2 or P == 5:
  for i, s in enumerate(S):
    s = int(s)
    if s % P == 0:
      ans += i+1
else:
  for key in c:
    ans += c[key]*(c[key]-1)//2

print(ans)

Submission status: Accepted

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

mods = [0] * (N+1)
for i in range(N-1, -1, -1):
  mods[i] = (int(S[i])*pow(10, N-i-1, P)+mods[i+1]) % P
c = dict()
for m in mods:
  c[m] = c.get(m, 0)+1

ans = 0
if P == 2 or P == 5:
  for i, s in enumerate(S):
    s = int(s)
    if s % P == 0:
      ans += i+1
else:
  for i in range(N):
    c[mods[i]] -= 1
    ans += c[mods[i]]

print(ans)

Submission status: Accepted

Solution code:
n,p = map(int,input().split())
s = input()
ans = 0
if p == 2 or p == 5:
    for i,c in enumerate(s,1):
        if int(c)%p == 0: ans += i
else:
    cnt = [0]*p
    cnt[0] = 1
    x = 0
    d = 1
    for c in s[::-1]:
        x += d*int(c)
        x %= p
        cnt[x%p] += 1
        d *= 10
        d %= p
    # print(cnt)
    for v in cnt: ans += v*(v-1)//2
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

def solve():
    input = sys.stdin.readline
    N, P = map(int, input().split())
    S = input().strip("\n")
    modSum = 0
    modDict = defaultdict(int)
    modDict[0] += 1
    ans = 0

    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):
            modSum += int(S[N-i-1]) * pow(10, i, P)
            modSum %= P
            modDict[modSum] += 1

        for key in modDict:
            v = modDict[key]
            ans += v * (v - 1) // 2
    
    print(ans)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

if P in {2, 5}:
    ans = 0
    for i, s in enumerate(S):
        if int(s) % P == 0:
            ans += i+1
else:
    ans = 0
    T = [0]*P
    T[0] = 1
    tmp = 0
    k = 1
    for s in reversed(S):
        tmp = (tmp + k * int(s)) % P
        k = k * 10 % P
        ans += T[tmp]
        T[tmp] += 1

print(ans)

Submission status: Accepted

Solution code:

def m():
    n,p=map(int,input().split())
    now=0
    s=input()
    if p==2 or p==5:
        ans=0
        for i in range(n):
            if int(s[i])%p:continue
            ans+=i+1
    else:
        table=[0]*p
        table[0]=1
        c=1
        for i in range(n-1,-1,-1):
            now=(now+c*int(s[i]))%p
            c=10*c%p
            table[now]+=1
        ans=sum(j*(j-1)//2 for j in table)

    print(ans)
if __name__ == "__main__":
    m()

Submission status: Accepted

Solution code:
# E - Divisible Substring
N,P = map(int,input().split())
S = input()
ans = 0
if P==2 or P==5:
    for i in range(N):
        if int(S[i])%P==0:
            ans += i+1
else:
    l = [1]+[0]*(P-1)
    tmp = 0
    r10 = 1
    for i in range(N-1,-1,-1):
        tmp = (r10*int(S[i])+tmp)%P
        l[tmp] += 1
        r10 = (r10*10)%P
    for x in l:
        ans += x*(x-1)//2
print(ans)

Submission status: Accepted

Solution code:
import sys 
import collections
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,P = map(int,readline().split())
S = list(map(int,readline().rstrip().decode()))

def solve_2(S):
    cnt = sum(i for i,x in enumerate(S,1) if x % 2 == 0)
    return cnt
def solve_5(S):
    cnt = sum(i for i,x in enumerate(S,1) if x % 5 == 0)
    return cnt
def solve(S):
    if P == 2:
        return solve_2(S)
    if P == 5:
        return solve_5(S)
    mod_cnt = [0]*(len(S))
    power = 1
    S = S[::-1]
    mod_cnt[0] = S[0] % P
    for i in range(1,len(S)):
        power *= 10
        power %= P
        mod_cnt[i] = (mod_cnt[i-1] + S[i] * power) % P
    c = collections.Counter(mod_cnt)
    cnt = sum( n*(n-1)//2 for n in c.values()) + c[0]
    return cnt

print(solve(S))

Submission status: Accepted

Solution code:
import sys 
import collections
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,P = map(int,readline().split())
S = list(map(int,readline().rstrip().decode()))

def solve_2(S):
    cnt = sum(i for i,x in enumerate(S,1) if x % 2 == 0)
    return cnt
def solve_5(S):
    cnt = sum(i for i,x in enumerate(S,1) if x % 5 == 0)
    return cnt
def solve(S):
    if P == 2:
        return solve_2(S)
    if P == 5:
        return solve_5(S)
    mod_cnt = [0]*(len(S))
    power = 1
    S = S[::-1]
    for i in range(len(S)):
        power *= 10
        power %= P
        mod_cnt[i] = (mod_cnt[i-1] + S[i] * power) % P
    c = collections.Counter(mod_cnt)
    cnt = sum( n*(n-1)//2 for n in c.values()) + c[0]
    return cnt

print(solve(S))

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n,p = map(int,ipt().split())
    s = input()
    ans = 0

    if p == 2:
        for i in range(n):
            if int(s[i])%2 == 0:
                ans += i+1
        print(ans)
    elif p == 5:
        for i in range(n):
            if int(s[i])%5 == 0:
                ans += i+1
        print(ans)
    else:
        d = defaultdict(int)
        pi = 0
        nk = 10%p
        for i in s[::-1]:
            pi = (pi+int(i)*nk)%p
            d[pi] += 1
            nk = (nk*10)%p
        for i in d.values():
            ans += i*(i-1)//2
        ans += d[0]
        print(ans)
    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    import collections
    N, P = map(int, input().split())
    S = input()[::-1]
    ans = 0
    if P == 2 or P == 5:
        for i, s in enumerate(S):
            if int(s) % P == 0:
                ans += N - i
    else:
        mod = [0] * P
        mod[0] = 1
        current = 0
        X = 1
        for s in S:
            current = (current + int(s) * X) % P
            ans += mod[current]
            mod[current] += 1
            X = X * 10 % P
    
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter

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

def check(n):
    ans = 0
    for i in range(1, N+1):
        v = int(S[-i])
        if v%n==0:
            ans += N-(i-1)
    return ans

ans = 0
if P==2:
    ans = check(2)
elif P==5:
    ans = check(5)
else:
    ac = [0]*(N+1)
    for i in range(1, N+1):
        ac[i] = (ac[i-1]+int(S[-i])*pow(10, i-1, P))%P
    c = Counter(ac)
    for i in c.values():
        ans += i*(i-1)//2

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

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

ans = 0

if P==2:
    for i in range(1, N+1):
        v = int(S[-i])
        if v%2==0:
            ans += N-(i-1)
elif P==5:
    for i in range(1, N+1):
        v = int(S[-i])
        if v%5==0:
            ans += N-(i-1)
else:
    ac = [0]*(N+1)
    for i in range(1, N+1):
        ac[i] = (ac[i-1]+int(S[-i])*pow(10, i-1, P))%P
    c = Counter(ac)
    for i in c.values():
        ans += i*(i-1)//2

print(ans)

Submission status: Accepted

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

count = 0

if(p == 2 or p == 5): #10と互いに素ではない場合
    co = 0
    for i in range(n): #1の位から順に数を追加していく
        ne = int(s[n-i-1]) % p
        if(ne == 0):
            co += 1
        count += co
    print(count)
else:
    sta = [0]*p
    sta[0] += 1
    d = 1
    co = 0
    for i in range(n):
        ne = int(s[n-i-1]) * d % p
        co += ne
        co %= p
        sta[co] += 1
        d *= 10
        d %= p
    for i in range(p):
        count += sta[i] * (sta[i]-1) // 2
    print(count)

Submission status: Accepted

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

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

    print(ans)
    exit()


mods=[0]*p
mods[0]=1
num=0
fac=1

for i in range(n):
    num+=(int(s[n-i-1])*fac)
    num%=p

    fac=(fac*10)
    fac%=p
    mods[num]+=1

#print(mods)
ans=0
for item in mods:
    ans+=(item*(item-1))//2

#print(len(s))
#print(mods)
print(ans)

Submission status: Accepted

Solution code:
## coding: UTF-8

N, P = map(int,input().split())
S = input()[::-1]


remainder = [0] * P
tmp = 0
rad = 1 #10**(i) % P

'''
if(P == 2 or P == 5):
    for i in range(N):
        r = int(S[i])
        tmp += r * rad
        tmp %= P
        remainder[tmp] += 1
        rad *= 10
'''
if(P == 2):
    ans = 0
    for i in range(N):
        r = int(S[i])
        if(r % 2 == 0):
            ans += N-i
    print(ans)
elif(P == 5):
    ans = 0
    for i in range(N):
        r = int(S[i])
        if(r % 5 == 0):
            ans += N-i
    print(ans)
else:
    for i in range(N):
        r = int(S[i])
        tmp += r * rad
        tmp %= P
        remainder[tmp] += 1
        rad *= 10
        rad %= P
    remainder[0] += 1

    #print(remainder)

    ans = 0
    for i in range(P):
        e = remainder[i]
        ans += e*(e-1)/2
    print(int(ans))

Submission status: Accepted

Solution code:
from collections import defaultdict
n,p = map(int,input().split())
s = list(map(int,list(input())))[::-1]
ans = 0
if p == 2 or p == 5:
    for i in range(n):
        if s[i]%p==0:
            ans += n-i
    print(ans)
else:
    d = defaultdict(int)
    check = 0
    ten = 1
    for i in range(n):
        check += s[i]*ten
        check %= p
        ans += d[check]
        if check == 0:
            ans+=1
        d[check] += 1
        ten *= 10
        ten %= p
    print(ans)

Submission status: Accepted

Solution code:
n, p = [int(_) for _ in 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)
    exit()

t = [0 for i in range(n+1)]
P = [0 for i in range(p)]
P[0] += 1
d = 1
for i in range(1, n+1):
    t[i] = (t[i-1]+int(s[n-i])*d) % p
    P[t[i]] += 1
    d = d*10 % p
ans = 0
for c in P:
    ans += c*(c-1)//2
# print(t)
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter
n,p=map(int,input().split())
s=input()
DP=[0]
ans=0

if p==2 or p==5:
    for i,j in enumerate(s):
        if int(j)%p==0:
            ans +=i+1
else:
    num,point=0,1
    for i in s[::-1]:
        num +=int(i)*point
        num %=p
        DP.append(num)
        point *=10
        point %=p

    DP=Counter(DP)
    for v,m in DP.items():
        if m>=2:ans +=m*(m-1)//2
print(ans)

Submission status: Accepted

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

ans = 0
if P == 2:
    for i in range(N-1, -1, -1):
        if int(S[i])%2 == 0:
            ans += i+1
elif P == 5:
    for i in range(N-1, -1, -1):
        if int(S[i])%5 == 0:
            ans += i+1
else:
    L = [0]*P
    num = 0
    for i in range(N-1, -1, -1):
        num += int(S[i])*pow(10, N-1-i, P)
        num %= P
        L[num] += 1

    ans += L[0]
    for i in range(P):
        ans += L[i]*(L[i]-1)//2

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

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

if P == 2:
    ret = 0
    for i in range(N):
        if int(S[i]) % 2 == 0:
           ret += i + 1
    print(ret)
    exit()

if P == 5:
    ret = 0
    for i in range(N):
        if int(S[i]) % 5 == 0:
           ret += i + 1
    print(ret)
    exit()

mods = [0] * (N+1)

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

cnt = Counter(mods)
ans = 0
for i in cnt:
    ans += cnt[i] * (cnt[i] - 1) // 2

print(ans)

Submission status: Accepted

Solution code:
N,P=map(int,input().split())
S=input()
list=[0 for _ in range(P)]
list[0]=1
now=0
a=0
if P==2 or P==5:
  M=len(S)
  S=reversed(S)
  l=0
  for s in S:
    if int(s)%P==0:
      a+=M-l
      l+=1
    else:
      l+=1
  print(a)
    

else:
  b=1
  h=0
  for s in reversed(S):
    h=h+b*int(s)
    list[h%P]+=1
    b=b*10%P
    
  c=0
  for i in range(len(list)):
    c+=list[i]*(list[i]-1)/2
  print(int(c))

Submission status: Accepted

Solution code:
#!python3

LI = lambda: list(map(int, input().split()))

# input
N, P = LI()
S = input()


def solve2():
    ans = 0
    for i in range(N):
        if int(S[i]) % 2 == 0:
            ans += i + 1
    return ans


def solve5():
    ans = 0
    for i in range(N):
        if int(S[i]) % 5 == 0:
            ans += i + 1
    return ans


def solve():
    d = [0] * P
    d[0] = 1
    w = 0
    ans = 0
    m = 1
    for s in S[::-1]:
        x = int(s)
        v = x * m % P
        w = (w + v) % P
        ans += d[w]
        d[w] += 1
        m = 10 * m % P
    return ans


def main():
    if P == 2:
        ans = solve2()
    elif P == 5:
        ans = solve5()
    else:
        ans = solve()
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

if P==5:
    ans = 0
    for i,m in enumerate(S):
        if m == '5' or m == '0':
            ans += i+1
elif P==2:
    ans = 0
    for i,m in enumerate(S):
        if int(m) % 2 ==0:
            ans += i+1
else:
    S = S[::-1]
    primdic = defaultdict(int)
    before = 0
    for i in range(0,N):
        now = (int(S[i])*pow(10,i,P)+before)%P
        primdic[now] += 1
        before = now
    # 文字なしの時はあまり0なので
    primdic[0] += 1
    ans = 0
    for value in primdic.values():
        ans += value*(value-1)//2
print(ans)

Submission status: Accepted

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

if P == 5:
    ans = 0
    for i in range(N):
        if S[i] == '5' or S[i] == '0':
            ans += i+1
elif P == 2:
    ans = 0
    for i in range(N):
        if int(S[i]) % 2 == 0:
            ans += i+1
else:
    M = defaultdict(int)
    before = 0
    S = S[::-1]
    for i in range(N):
        now = (int(S[i])*(pow(10, i+1, P)) + before) % P
        before = now
        M[now] += 1
    M[0] += 1
    ans = 0
    for value in M.values():
        ans += value*(value-1)//2
print(ans)