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

Solution in Rust (1.15.1) (judge verdict: Accepted)

#[allow(unused_imports)]
use std::cmp::{Ordering};

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};

#[allow(unused_imports)]
use std::iter::FromIterator;

#[allow(unused_macros)]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::min($x, min!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::max($x, max!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! get { 
    ([$t: ty]) => { 
        { 
            let mut line = String::new(); 
            stdin().read_line(&mut line).unwrap(); 
            line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::<Vec<_>>()
        }
    };
    ([$t: ty];$n: expr) => {
        (0..$n).map(|_|get!([$t])).collect::<Vec<_>>()
    };
    ($t: ty) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t: ty),*) => {
        { 
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*)
        }
    };
    ($t: ty; $n: expr) => {
        (0..$n).map(|_|get!($t)).collect::<Vec<_>>()
    };
    ($($t: ty),*; $n: expr) => {
        (0..$n).map(|_|get!($($t),*)).collect::<Vec<_>>()
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*).unwrap();
    }
}

const BIG_STACK_SIZE: bool = true;

#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}

use self::modint::ModInt;
mod modint {
    use std;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
    pub struct ModInt {
        pub value: usize,
        module: usize,
    }
    impl ModInt {
        pub fn new(value: usize, module: usize) -> Self {
            ModInt {
                value: value % module,
                module: module,
            }
        }
    }
    impl std::ops::Add for ModInt {
        type Output = Self;
        fn add(self, other: Self) -> Self {
            let mut value = self.value + other.value;
            if value > self.module {
                value -= self.module;
            }
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::Add<usize> for ModInt {
        type Output = Self;
        fn add(self, other: usize) -> Self {
            let mut value = self.value + other;
            if value > self.module {
                value -= self.module;
            }
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::Sub for ModInt {
        type Output = Self;
        fn sub(self, other: Self) -> Self {
            let mut value = self.value;
            if value < other.value {
                value += self.module;
            }
            value -= other.value;
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::Sub<usize> for ModInt {
        type Output = Self;
        fn sub(self, other: usize) -> Self {
            let mut value = self.value;
            if value < other {
                value += self.module;
            }
            value -= other;
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::Mul for ModInt {
        type Output = Self;
        fn mul(self, other: Self) -> Self {
            let value = self.value * other.value % self.module;
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::Mul<usize> for ModInt {
        type Output = Self;
        fn mul(self, other: usize) -> Self {
            let value = self.value * other % self.module;
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::Div for ModInt {
        type Output = Self;
        fn div(self, other: Self) -> Self {
            let mut exp = self.module - 2;
            let mut value = self.value;
            let mut ovalue = other.value;
            while exp > 0 {
                if exp % 2 == 1 {
                    value = value * ovalue % self.module;
                }
                ovalue = ovalue * ovalue % self.module;
                exp /= 2;
            }
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::Div<usize> for ModInt {
        type Output = Self;
        fn div(self, other: usize) -> Self {
            let mut exp = self.module - 2;
            let mut value = self.value;
            let mut ovalue = other;
            while exp > 0 {
                if exp % 2 == 1 {
                    value = value * ovalue % self.module;
                }
                ovalue = ovalue * ovalue % self.module;
                exp /= 2;
            }
            ModInt::new(value, self.module)
        }
    }
    impl std::ops::AddAssign for ModInt {
        fn add_assign(&mut self, other: Self) {
            *self = *self + other;
        }
    }
    impl std::ops::AddAssign<usize> for ModInt {
        fn add_assign(&mut self, other: usize) {
            *self = *self + other;
        }
    }
    impl std::ops::SubAssign for ModInt {
        fn sub_assign(&mut self, other: Self) {
            *self = *self - other;
        }
    }
    impl std::ops::SubAssign<usize> for ModInt {
        fn sub_assign(&mut self, other: usize) {
            *self = *self - other;
        }
    }
    impl std::ops::MulAssign for ModInt {
        fn mul_assign(&mut self, other: Self) {
            *self = *self * other;
        }
    }
    impl std::ops::MulAssign<usize> for ModInt {
        fn mul_assign(&mut self, other: usize) {
            *self = *self * other;
        }
    }
    impl std::ops::DivAssign for ModInt {
        fn div_assign(&mut self, other: Self) {
            *self = *self / other;
        }
    }
    impl std::ops::DivAssign<usize> for ModInt {
        fn div_assign(&mut self, other: usize) {
            *self = *self / other;
        }
    }
    impl std::fmt::Debug for ModInt {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "{}", self.value)
        }
    }
    impl std::fmt::Display for ModInt {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "{}", self.value)
        }
    }
}

fn pow10(n: usize, p: usize) -> ModInt {
    let mut res = ModInt::new(1,p);
    let mut beki = ModInt::new(10,p);
    let mut n = n;
    while n > 0 {
        if n % 2 > 0 {
            res *= beki;
        }
        beki *= beki;
        n /= 2;
    }
    res
}

fn solve() {
    let (n,p) = get!(usize, usize);
    let s = get!(String).chars().map(|e| e as usize - '0' as usize).collect::<Vec<_>>();

    let mut res = 0usize;
    if p == 2 || p == 5 {
        for i in (0..n).rev() {
            if s[i] % p == 0 {
                res += i+1;
            }
        }
    } else {
        let mut vec = vec![0usize; p];
        let mut val = ModInt::new(0, p);
        for i in (0..n).rev() {
            val = val+pow10(n-i-1,p)*s[i];
            res += vec[val.value];
            if val.value == 0 {
                res += 1;
            }
            vec[val.value] += 1;
        }
    }
    println!("{}", res);
}