//---------- begin union_find ----------
pub struct DSU {
    p: Vec<i32>,
}
impl DSU {
    pub fn new(n: usize) -> DSU {
        assert!(n < std::i32::MAX as usize);
        DSU { p: vec![-1; n] }
    }
    pub fn init(&mut self) {
        self.p.iter_mut().for_each(|p| *p = -1);
    }
    pub fn root(&self, mut x: usize) -> usize {
        assert!(x < self.p.len());
        while self.p[x] >= 0 {
            x = self.p[x] as usize;
        }
        x
    }
    pub fn same(&self, x: usize, y: usize) -> bool {
        assert!(x < self.p.len() && y < self.p.len());
        self.root(x) == self.root(y)
    }
    pub fn unite(&mut self, x: usize, y: usize) -> Option<(usize, usize)> {
        assert!(x < self.p.len() && y < self.p.len());
        let mut x = self.root(x);
        let mut y = self.root(y);
        if x == y {
            return None;
        }
        if self.p[x] > self.p[y] {
            std::mem::swap(&mut x, &mut y);
        }
        self.p[x] += self.p[y];
        self.p[y] = x as i32;
        Some((x, y))
    }
    pub fn parent(&self, x: usize) -> Option<usize> {
        assert!(x < self.p.len());
        let p = self.p[x];
        if p >= 0 {
            Some(p as usize)
        } else {
            None
        }
    }
    pub fn sum<F>(&self, mut x: usize, mut f: F) -> usize
    where
        F: FnMut(usize),
    {
        while let Some(p) = self.parent(x) {
            f(x);
            x = p;
        }
        x
    }
    pub fn size(&self, x: usize) -> usize {
        assert!(x < self.p.len());
        let r = self.root(x);
        (-self.p[r]) as usize
    }
}
//---------- end union_find ----------
// ---------- begin Matrix ----------
mod matrix {
    use std::ops::*;
    pub trait SemiRing: Add<Output = Self> + Mul<Output = Self> + Copy {
        fn zero() -> Self;
        fn one() -> Self;
    }
    pub trait Inverse: SemiRing {
        fn is_zero() -> bool;
        fn inv(self) -> Self;
    }
    #[derive(Clone)]
    pub struct SquareMatrix<R> {
        size: usize,
        buf: Box<[R]>,
    }
    #[allow(dead_code)]
    impl<R: SemiRing> SquareMatrix<R> {
        pub fn zero(size: usize) -> Self {
            SquareMatrix {
                size: size,
                buf: vec![R::zero(); size * size].into_boxed_slice(),
            }
        }
        pub fn identity(size: usize) -> Self {
            let mut e = Self::zero(size);
            for i in 0..size {
                e.buf[i * size + i] = R::one();
            }
            e
        }
        pub fn set_at(&mut self, x: usize, y: usize, val: R) {
            assert!(x < self.size && y < self.size);
            self.buf[x * self.size + y] = val;
        }
        pub fn get_at(&self, x: usize, y: usize) -> R {
            assert!(x < self.size && y < self.size);
            self.buf[x * self.size + y]
        }
        pub fn get_mut(&mut self, x: usize, y: usize) -> &mut R {
            assert!(x < self.size && y < self.size);
            &mut self.buf[x * self.size + y]
        }
        pub fn matadd(&self, rhs: &Self) -> Self {
            assert!(self.size == rhs.size);
            let buf: Vec<R> = self
                .buf
                .iter()
                .zip(rhs.buf.iter())
                .map(|p| *p.0 + *p.1)
                .collect();
            SquareMatrix {
                size: self.size,
                buf: buf.into_boxed_slice(),
            }
        }
        pub fn matmul(&self, rhs: &Self) -> Self {
            let size = self.size;
            assert!(size == rhs.size);
            let mut res = Self::zero(size);
            for (x, a) in res.buf.chunks_mut(size).zip(self.buf.chunks(size)) {
                for (a, b) in a.iter().zip(rhs.buf.chunks(size)) {
                    for (x, b) in x.iter_mut().zip(b.iter()) {
                        *x = *x + *a * *b;
                    }
                }
            }
            res
        }
        pub fn mat_pow(&self, mut n: usize) -> Self {
            let size = self.size;
            let mut t = Self::identity(size);
            let mut s = self.clone();
            while n > 0 {
                if n & 1 == 1 {
                    t = t.matmul(&s);
                }
                s = s.matmul(&s);
                n >>= 1;
            }
            t
        }
    }
    #[allow(dead_code)]
    impl<R: SemiRing + Sub<Output = R>> SquareMatrix<R> {
        pub fn matsub(&self, rhs: &Self) -> Self {
            assert!(self.size == rhs.size);
            let buf: Vec<R> = self
                .buf
                .iter()
                .zip(rhs.buf.iter())
                .map(|p| *p.0 - *p.1)
                .collect();
            SquareMatrix {
                size: self.size,
                buf: buf.into_boxed_slice(),
            }
        }
    }
    /*
    #[allow(dead_code)]
    impl<R: Inverse + Sub<Output = R>> SquareMatrix<R> {
        pub fn inverse(&self) -> Self {
        }
    }
    */
}
// ---------- end Matrix ----------
// ---------- begin ModInt ----------
// モンゴメリ乗算を用いる
// ほぼCodeforces用
// 注意
// new_unchecked は値xが 0 <= x < modulo であることを仮定
// ModInt の中身は正規化された値で持ってるので直接読んだり書いたりするとぶっ壊れる
// 奇素数のみ
mod modint {

    use std::marker::*;
    use std::ops::*;

    pub trait Modulo {
        fn modulo() -> u32;
        fn rem() -> u32;
        fn ini() -> u64;
        fn reduce(x: u64) -> u32 {
            assert!(x < (Self::modulo() as u64) << 32);
            let b = (x as u32 * Self::rem()) as u64;
            let t = x + b * Self::modulo() as u64;
            let mut c = (t >> 32) as u32;
            if c >= Self::modulo() {
                c -= Self::modulo();
            }
            c as u32
        }
    }

    #[allow(dead_code)]
    pub enum Mod1_000_000_007 {}

    impl Modulo for Mod1_000_000_007 {
        fn modulo() -> u32 {
            1_000_000_007
        }
        fn rem() -> u32 {
            2226617417
        }
        fn ini() -> u64 {
            582344008
        }
    }

    #[allow(dead_code)]
    pub enum Mod998_244_353 {}

    impl Modulo for Mod998_244_353 {
        fn modulo() -> u32 {
            998_244_353
        }
        fn rem() -> u32 {
            998244351
        }
        fn ini() -> u64 {
            932051910
        }
    }

    #[allow(dead_code)]
    pub fn generate_umekomi_modulo(p: u32) {
        assert!(
            p < (1 << 31)
                && p > 2
                && p & 1 == 1
                && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0)
        );
        let mut t = 1u32;
        let mut s = !p + 1;
        let mut n = !0u32 >> 2;
        while n > 0 {
            if n & 1 == 1 {
                t *= s;
            }
            s *= s;
            n >>= 1;
        }
        let mut ini = (1u64 << 32) % p as u64;
        ini = (ini << 32) % p as u64;
        assert!(t * p == !0);
        println!("pub enum Mod{} {{}}", p);
        println!("impl Modulo for Mod{} {{", p);
        println!("    fn modulo() -> u32 {{");
        println!("        {}", p);
        println!("    }}");
        println!("    fn rem() -> u32 {{");
        println!("        {}", t);
        println!("    }}");
        println!("    fn ini() -> u32 {{");
        println!("        {}", ini);
        println!("    }}");
        println!("}}");
        let mut f = vec![];
        let mut n = p - 1;
        for i in 2.. {
            if i * i > n {
                break;
            }
            if n % i == 0 {
                f.push(i);
                while n % i == 0 {
                    n /= i;
                }
            }
        }
        if n > 1 {
            f.push(n);
        }
        let mut order = 1;
        let mut n = p - 1;
        while n % 2 == 0 {
            n /= 2;
            order <<= 1;
        }
        let z = (2u64..)
            .find(|z| {
                f.iter()
                    .all(|f| mod_pow(*z, ((p - 1) / *f) as u64, p as u64) != 1)
            })
            .unwrap();
        let zeta = mod_pow(z, ((p - 1) / order) as u64, p as u64);
        println!("impl transform::NTTFriendly for Mod{} {{", p);
        println!("    fn order() -> usize {{");
        println!("        {}", order);
        println!("    }}");
        println!("    fn zeta() -> u32 {{");
        println!("        {}", zeta);
        println!("    }}");
        println!("}}");
    }

    pub struct ModInt<T>(u32, PhantomData<T>);

    impl<T> Clone for ModInt<T> {
        fn clone(&self) -> Self {
            ModInt::build(self.0)
        }
    }

    impl<T> Copy for ModInt<T> {}

    impl<T: Modulo> Add for ModInt<T> {
        type Output = ModInt<T>;
        fn add(self, rhs: Self) -> Self::Output {
            let mut d = self.0 + rhs.0;
            if d >= T::modulo() {
                d -= T::modulo();
            }
            Self::build(d)
        }
    }

    impl<T: Modulo> AddAssign for ModInt<T> {
        fn add_assign(&mut self, rhs: Self) {
            *self = *self + rhs;
        }
    }

    impl<T: Modulo> Sub for ModInt<T> {
        type Output = ModInt<T>;
        fn sub(self, rhs: Self) -> Self::Output {
            let mut d = T::modulo() + self.0 - rhs.0;
            if d >= T::modulo() {
                d -= T::modulo();
            }
            Self::build(d)
        }
    }

    impl<T: Modulo> SubAssign for ModInt<T> {
        fn sub_assign(&mut self, rhs: Self) {
            *self = *self - rhs;
        }
    }

    impl<T: Modulo> Mul for ModInt<T> {
        type Output = ModInt<T>;
        fn mul(self, rhs: Self) -> Self::Output {
            Self::build(T::reduce(self.0 as u64 * rhs.0 as u64))
        }
    }

    impl<T: Modulo> MulAssign for ModInt<T> {
        fn mul_assign(&mut self, rhs: Self) {
            *self = *self * rhs;
        }
    }

    impl<T: Modulo> Neg for ModInt<T> {
        type Output = ModInt<T>;
        fn neg(self) -> Self::Output {
            if self.0 == 0 {
                Self::zero()
            } else {
                Self::build(T::modulo() - self.0)
            }
        }
    }

    impl<T: Modulo> std::fmt::Display for ModInt<T> {
        fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
            write!(f, "{}", self.get())
        }
    }

    impl<T: Modulo> std::fmt::Debug for ModInt<T> {
        fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
            write!(f, "{}", self.get())
        }
    }

    impl<T: Modulo> std::str::FromStr for ModInt<T> {
        type Err = std::num::ParseIntError;
        fn from_str(s: &str) -> Result<Self, Self::Err> {
            let val = s.parse::<u32>()?;
            Ok(ModInt::new(val))
        }
    }

    impl<T: Modulo> From<usize> for ModInt<T> {
        fn from(val: usize) -> ModInt<T> {
            ModInt::new_unchecked((val % T::modulo() as usize) as u32)
        }
    }

    impl<T: Modulo> From<u64> for ModInt<T> {
        fn from(val: u64) -> ModInt<T> {
            ModInt::new_unchecked((val % T::modulo() as u64) as u32)
        }
    }

    impl<T: Modulo> From<i64> for ModInt<T> {
        fn from(val: i64) -> ModInt<T> {
            let m = T::modulo() as i64;
            ModInt::new((val % m + m) as u32)
        }
    }

    #[allow(dead_code)]
    impl<T> ModInt<T> {
        fn build(d: u32) -> Self {
            ModInt(d, PhantomData)
        }
        pub fn zero() -> Self {
            Self::build(0)
        }
        pub fn is_zero(&self) -> bool {
            self.0 == 0
        }
    }

    #[allow(dead_code)]
    impl<T: Modulo> ModInt<T> {
        pub fn new_unchecked(d: u32) -> Self {
            Self::build(T::reduce(d as u64 * T::ini()))
        }
        pub fn new(d: u32) -> Self {
            Self::new_unchecked(d % T::modulo())
        }
        pub fn one() -> Self {
            Self::new_unchecked(1)
        }
        pub fn get(&self) -> u32 {
            T::reduce(self.0 as u64)
        }
        pub fn pow(&self, mut n: u64) -> Self {
            let mut t = Self::one();
            let mut s = *self;
            while n > 0 {
                if n & 1 == 1 {
                    t *= s;
                }
                s *= s;
                n >>= 1;
            }
            t
        }
        pub fn inv(&self) -> Self {
            assert!(!self.is_zero());
            self.pow((T::modulo() - 2) as u64)
        }
    }

    pub fn mod_pow(mut r: u64, mut n: u64, m: u64) -> u64 {
        let mut t = 1 % m;
        while n > 0 {
            if n & 1 == 1 {
                t = t * r % m;
            }
            r = r * r % m;
            n >>= 1;
        }
        t
    }
}
// ---------- end ModInt ----------

use modint::*;

type M = ModInt<Mod998_244_353>;

// ---------- begin input macro ----------
// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
// ---------- end input macro ----------

// 行列累乗っぽいが状態数厳しげでは...

use matrix::*;
type Mat = SquareMatrix<M>;

impl SemiRing for M {
    fn zero() -> Self {
        M::zero()
    }
    fn one() -> Self {
        M::one()
    }
}

fn lcp(x: &[u8], y: &[u8]) -> usize {
    x.iter().zip(y).take_while(|p| *p.0 == *p.1).count()
}

fn run() {
    input! {
        n: usize,
        m: usize,
        s: [bytes; n],
    }
    let mut id = 0;
    let mut map = std::collections::BTreeMap::new();
    for s in s.iter() {
        for i in 0..s.len() {
            let s = s[i..].iter().cloned().collect::<Vec<_>>();
            map.entry(s).or_insert_with(|| {
                let v = id;
                id += 1;
                v
            });
        }
    }
    map.insert(vec![], id);
    id += 1;
    let mut edge = vec![];
    for (x, &src) in map.iter() {
        if x.is_empty() {
            for a in s.iter() {
                for b in s.iter() {
                    let len = lcp(a, b);
                    let a = a[len..].iter().cloned().collect::<Vec<_>>();
                    let b = b[len..].iter().cloned().collect::<Vec<_>>();
                    if !a.is_empty() && !b.is_empty() {
                        continue;
                    }
                    let mut pre = src;
                    for _ in 1..len {
                        edge.push((pre, id));
                        pre = id;
                        id += 1;
                    }
                    if a.is_empty() {
                        let dst = *map.get(&b).unwrap();
                        edge.push((pre, dst));
                    } else if b.is_empty() {
                        let dst = *map.get(&a).unwrap();
                        edge.push((pre, dst));
                    }
                }
            }
        } else {
            for a in s.iter() {
                let len = lcp(a, x);
                let a = a[len..].iter().cloned().collect::<Vec<_>>();
                let b = x[len..].iter().cloned().collect::<Vec<_>>();
                if !a.is_empty() && !b.is_empty() {
                    continue;
                }
                let mut pre = src;
                for _ in 1..len {
                    edge.push((pre, id));
                    pre = id;
                    id += 1;
                }
                if a.is_empty() {
                    let dst = *map.get(&b).unwrap();
                    edge.push((pre, dst));
                } else if b.is_empty() {
                    let dst = *map.get(&a).unwrap();
                    edge.push((pre, dst));
                }
            }
        }
    }
    let src = *map.get(&vec![]).unwrap();
    let mut dsu = DSU::new(id);
    for &(a, b) in edge.iter() {
        dsu.unite(a, b);
    }
    let mut index = vec![id; id];
    let mut p = 0;
    for i in 0..id {
        if dsu.same(i, src) {
            index[i] = p;
            p += 1;
        }
    }
    let mut mat = Mat::zero(p);
    for &(a, b) in edge.iter() {
        if index[a] < id {
            *mat.get_mut(index[a], index[b]) += M::one();
        }
    }
    let pow = mat.mat_pow(m);
    let ans = pow.get_at(index[src], index[src]);
    println!("{}", ans);
}

fn main() {
    run();
}


use std::io;
use std::str::FromStr;

use std::io::prelude::*;
use std::io::BufReader;
use std::cmp::{max, min};

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

const p: i64 = 1_000_000_007;

fn main() {
    let (n, m, k) = {
        let input = get_line();
        let mut it = input.split_whitespace().map(|x| x.parse::<i64>().unwrap());
        (
            it.next().unwrap(),
            it.next().unwrap(),
            it.next().unwrap(),
            )
    };

    // (2^{n - 1})^{m - 1}
    // 2^{n + m - 2}

    if k == -1 && (n + m) % 2 != 0 {
        println!("0");
        return;
    }

    let n0 = {
        let p0 = p - 1;
        ((n - 1) % p0) * ((m - 1) % p0) % p0
    };

    let mut two_pow_two_pow = Vec::new();

    let mul = |a, b| {
        ((a % p) * (b % p)) % p
    };

    let mut i = 2;
    for _ in 0..40 {
        two_pow_two_pow.push(i);
        i = mul(i, i);
    }

    let mut ans = 1;

    for i in 0..40 {
        if n0 & (1 << i) != 0 {
            ans = mul(ans, two_pow_two_pow[i]);
        }
    }

    println!("{}", ans);
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

const MOD: u64 = 1_000_000_007;

fn mod_pow(r: u64, mut n: u64) -> u64 {
    let mut t = 1;
    let mut s = r % MOD;
    while n > 0 {
        if n & 1 == 1 {
            t = t * s % MOD;
        }
        s = s * s % MOD;
        n >>= 1;
    }
    t
}

fn run() {
    input! {
        n: u64,
        m: u64,
        k: i32,
    }
    if k == -1 && m % 2 != n % 2 {
        println!("0");
        return;
    }
    let ans = mod_pow(mod_pow(2, n - 1), m - 1);
    println!("{}", ans);
}

fn main() {
    run();
}


fn read_line() -> String {
    let stdin = std::io::stdin();
    let mut line = String::new();
    stdin.read_line(&mut line).unwrap();
    String::from(line.trim())
}

macro_rules! scan_line {
    ($($ty: ty),*) => {{
        let line = read_line();
        let mut tok = line.split_whitespace();
        ($(tok.next().unwrap().parse::<$ty>().unwrap()),*)
    }}
}

const MOD: i64 = 1_000_000_007;

fn pow_with_mod(mut a: i64, mut n: i64) -> i64 {
    let mut acc = 1;
    a = a % MOD;
    while n > 0 {
        if n & 1 == 1 {
            acc = (acc * a) % MOD;
        }
        a = (a * a) % MOD;
        n >>= 1;
    }
    acc
}

fn main() {
    let (n, m, k) = scan_line!(i64, i64, i32);
    let ans = if n % 2 != m % 2 && k == -1 {
        0
    } else {
        pow_with_mod(pow_with_mod(2, n - 1), m - 1)
    };
    println!("{}", ans);
}


use std::io::stdin;
fn main() {
    let (a, b) = parse();
    let mut values = 0;
    for i in a..b + 1 {
        for c in i.to_string().chars() {
            values += calculate_segment(c)
        }
    }
    println!("{}", values)
}
fn parse() -> (usize, usize) {
    let mut text = String::new();
    stdin().read_line(&mut text).unwrap();
    let text: Vec<usize> = text
        .trim()
        .split_whitespace()
        .map(|e| e.parse().unwrap())
        .collect();
    (text[0], text[1])
}
fn calculate_segment(ch: char) -> usize {
    match ch {
        '0' | '6' | '9' => 6,
        '1' => 2,
        '2' | '3' | '5' => 5,
        '4' => 4,
        '7' => 3,
        '8' => 7,
        _ => 0,
    }
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, [graph1; $len:expr]) => {{
        let mut g = vec![vec![]; $len];
        let ab = read_value!($next, [(usize1, usize1)]);
        for (a, b) in ab {
            g[a].push(b);
            g[b].push(a);
        }
        g
    }};
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };
    ($next:expr, usize1) => (read_value!($next, usize) - 1);
    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        read_value!($next, [$t; len])
    }};
    ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

/// Verified by https://atcoder.jp/contests/arc093/submissions/3968098
mod mod_int {
    use std::ops::*;
    pub trait Mod: Copy { fn m() -> i64; }
    #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
    pub struct ModInt<M> { pub x: i64, phantom: ::std::marker::PhantomData<M> }
    impl<M: Mod> ModInt<M> {
        // x >= 0
        pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }
        fn new_internal(x: i64) -> Self {
            ModInt { x: x, phantom: ::std::marker::PhantomData }
        }
        pub fn pow(self, mut e: i64) -> Self {
            debug_assert!(e >= 0);
            let mut sum = ModInt::new_internal(1);
            let mut cur = self;
            while e > 0 {
                if e % 2 != 0 { sum *= cur; }
                cur *= cur;
                e /= 2;
            }
            sum
        }
        #[allow(dead_code)]
        pub fn inv(self) -> Self { self.pow(M::m() - 2) }
    }
    impl<M: Mod, T: Into<ModInt<M>>> Add<T> for ModInt<M> {
        type Output = Self;
        fn add(self, other: T) -> Self {
            let other = other.into();
            let mut sum = self.x + other.x;
            if sum >= M::m() { sum -= M::m(); }
            ModInt::new_internal(sum)
        }
    }
    impl<M: Mod, T: Into<ModInt<M>>> Sub<T> for ModInt<M> {
        type Output = Self;
        fn sub(self, other: T) -> Self {
            let other = other.into();
            let mut sum = self.x - other.x;
            if sum < 0 { sum += M::m(); }
            ModInt::new_internal(sum)
        }
    }
    impl<M: Mod, T: Into<ModInt<M>>> Mul<T> for ModInt<M> {
        type Output = Self;
        fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }
    }
    impl<M: Mod, T: Into<ModInt<M>>> AddAssign<T> for ModInt<M> {
        fn add_assign(&mut self, other: T) { *self = *self + other; }
    }
    impl<M: Mod, T: Into<ModInt<M>>> SubAssign<T> for ModInt<M> {
        fn sub_assign(&mut self, other: T) { *self = *self - other; }
    }
    impl<M: Mod, T: Into<ModInt<M>>> MulAssign<T> for ModInt<M> {
        fn mul_assign(&mut self, other: T) { *self = *self * other; }
    }
    impl<M: Mod> Neg for ModInt<M> {
        type Output = Self;
        fn neg(self) -> Self { ModInt::new(0) - self }
    }
    impl<M> ::std::fmt::Display for ModInt<M> {
        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            self.x.fmt(f)
        }
    }
    impl<M: Mod> ::std::fmt::Debug for ModInt<M> {
        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            let (mut a, mut b, _) = red(self.x, M::m());
            if b < 0 {
                a = -a;
                b = -b;
            }
            write!(f, "{}/{}", a, b)
        }
    }
    impl<M: Mod> From<i64> for ModInt<M> {
        fn from(x: i64) -> Self { Self::new(x) }
    }
    // Finds the simplest fraction x/y congruent to r mod p.
    // The return value (x, y, z) satisfies x = y * r + z * p.
    fn red(r: i64, p: i64) -> (i64, i64, i64) {
        if r.abs() <= 10000 {
            return (r, 1, 0);
        }
        let mut nxt_r = p % r;
        let mut q = p / r;
        if 2 * nxt_r >= r {
            nxt_r -= r;
            q += 1;
        }
        if 2 * nxt_r <= -r {
            nxt_r += r;
            q -= 1;
        }
        let (x, z, y) = red(nxt_r, r);
        (x, y - q * z, z)
    }
} // mod mod_int

macro_rules! define_mod {
    ($struct_name: ident, $modulo: expr) => {
        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        struct $struct_name {}
        impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }
    }
}
const MOD: i64 = 1_000_000_007;
define_mod!(P, MOD);
type ModInt = mod_int::ModInt<P>;

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (let _ = write!(out,$($format)*););
    }
    input! {
        k: usize, pa: i64, pb: i64,
    }
    let mut dp = vec![vec![ModInt::new(0); k + 1]; k + 1];
    let pa = ModInt::new(pa);
    let pb = ModInt::new(pb);
    let pab = pa + pb;
    let pabinv = pab.inv();
    for i in (0..k).rev() {
        dp[i][k] = pa * pb.inv() + ModInt::new((i + k) as i64);
        for j in (1..k).rev() {
            let mut val = dp[i][j + 1] * pa;
            if i + j < k {
                val += dp[min(k, i + j)][j] * pb;
            } else {
                val += pb * ModInt::new((i + j) as i64);
            }
            dp[i][j] = val * pabinv;
        }
        let val = dp[i][1];
        dp[i][0] = val;
    }
    puts!("{}\n", dp[0][0]);
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


use std::io;
use std::io::Read;

fn main() {
    let mut text = String::new();
    io::stdin().read_to_string(&mut text).unwrap();
    let mut iter = text.split_whitespace();//.map(|x| x.parse::<i64>().unwrap());
    let n = iter.next().unwrap().parse::<i64>().unwrap();
    let s = iter.next().unwrap();
    let mut up = true;
    let mut down = true;
    let mut left = true;
    let mut right = true;
    for c in s.chars() {
        let d = c as i64 - '0' as i64;
        if d == 1 || d == 2 || d == 3 {
            up = false;
        }
        if d == 7 || d == 9 || d == 0 {
            down = false;
        }
        if d == 1 || d == 4 || d == 7 || d == 0 {
            left = false;
        }
        if d == 3 || d == 6 || d == 9 || d == 0 {
            right = false;
        }
    }
    println!("{}", if (up || down || left || right) {"NO"} else {"YES"});

}

fn get_pos(num: i64) -> (i64, i64) {
    if num == 0 {
        (3, 1)
    } else {
        ((num - 1) / 3, (num - 1) % 3)
    }
}


use std::io::BufRead;
use std::io::Write;

#[derive(Debug,Clone,Copy,Default)]
struct Problem {
    buf: [u8;9],
    len: u8,
}

impl Problem {
    fn as_slice(&self) -> &[u8] {
        &self.buf[0..self.len as usize]
    }
}

fn loc(d: u8) -> (u8,u8) {
    assert!(d < 10);
    if d == 0 {
        (1,3)
    } else {
        ((d-1)%3,(d-1)/3)
    }
}

fn read_problem() -> Problem {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();

    let ct = str::parse::<u8>(&lines.next().unwrap().unwrap()).unwrap();
    let mut ret = Problem::default();
    for (c,b) in lines.next().unwrap().unwrap().chars().zip(ret.buf.iter_mut()) {
        *b = c.to_digit(10).unwrap() as u8;
        ret.len += 1;
    }
    assert_eq!(ret.len, ct);
    assert!(lines.next().is_none());
    ret
}

fn solve(problem: Problem) -> bool {
    let mut min_x = u8::max_value();
    let mut min_y = u8::max_value();
    let mut max_x = 0;
    let mut max_y = 0;
    let mut max_side_y = 0;

    for &d in problem.as_slice() {
        let (x,y) = loc(d);
        if x < min_x {
            min_x = x;
        }
        if x > max_x {
            max_x = x;
        }
        if y < min_y {
            min_y = y;
        }
        if y > max_y {
            max_y = y;
        }
        if x != 1 && y > max_side_y  {
            max_side_y = y;
        }
    }

    let dx = max_x - min_x;
    let dy = max_y - min_y;
    let dsy = max_side_y - min_y;
    writeln!(&mut std::io::stderr(), "{:?}", (dx,dy,dsy)).unwrap();
    dy == 3 || (dx,dsy) == (2,2)
}

fn main() {
    let p = read_problem();
    println!("{}", if solve(p) { "YES" } else { "NO" });
}


use std::io::stdin;

fn get_input(input: &mut String) {
    input.clear();
    stdin().read_line(input).expect("error");
}

fn main() {
    let mut input = String::new();

    get_input(&mut input);
    let mut numbers = input.trim().split_whitespace();
    let n = numbers.next().unwrap().parse::<u64>().unwrap();
    let k = numbers.next().unwrap().parse::<u64>().unwrap();
    let max_price = std::cmp::min(n, k-1);
    let min_price = k - max_price;
    if min_price >= max_price {
        println!("0");
    } else {
        let length = max_price - min_price;
        println!("{}", length / 2 + length % 2);
    }
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn run() {
    input! {
        n: i64,
        k: i64,
    }
    let l = std::cmp::max(1, k - n);
    let ans = if k % 2 == 1 {
        let r = k / 2;
        if r + 1 > n || l > r {
            0
        } else {
            r - l + 1
        }
    } else {
        let r = k / 2 - 1;
        if r + 2 > n || l > r {
            0
        } else {
            r - l + 1
        }
    };
    println!("{}", ans);
}

fn main() {
    run();
}


#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

// -----------------------------------------------
// Framework <https://github.com/vain0x/procon>
// -----------------------------------------------

#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($t:ty) =>
        (rl().parse::<$t>().unwrap());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($arg:expr),*) => {
        #[cfg(debug_assertions)]
        $(writeln!(stderr(), "{} = {:?}", stringify!($arg), $arg).unwrap());*
    };
}

#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim_right().to_owned()
}

trait IteratorExt: Iterator + Sized {
    fn vec(self) -> Vec<Self::Item> {
        self.collect()
    }
}

impl<T: Iterator> IteratorExt for T {}

// -----------------------------------------------
// Solution
// -----------------------------------------------

fn solve(N: i64, K: i64) -> i64 {
    let r = min(N + 1, K);
    let l = min(r, K / 2 + 1);
    r - l
}

fn main() {
    let (N, K) = read!(i64, i64);
    println!("{}", solve(N, K))
}

#[cfg(test)]
mod tests {
    use super::solve;

    #[test]
    fn tests() {
        assert_eq!(solve(8, 5), 2);
        assert_eq!(solve(8, 15), 1);
        assert_eq!(solve(7, 20), 0);
        assert_eq!(solve(1000000000000, 1000000000001), 500000000000);

        assert_eq!(solve(1, 1), 0);
        assert_eq!(solve(2, 3), 1);
    }
}


macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

fn solve() {
    let (a, x, y) = parse_line!(i64, i64, i64);
    if y <= 0 || y % a == 0 || x.abs() >= a {
        return println!("-1");
    }
    if y < a {
        if (x * 2).abs() < a {
            println!("1");
        }else{
            println!("-1");
        }
        return;
    }
    let y = y - a;
    let period = y / (2 * a);
    let left = y % (2 * a);
    if left < a {
        if (x * 2).abs() < a {
            println!("{}", 2 + period * 3);
        }else{
            println!("-1");
        }
    }else{
        if x < 0 {
            println!("{}", 3 + period * 3);
        }else if x > 0 {
            println!("{}", 4 + period * 3);
        }else{
            println!("-1");
        }
    }
}

fn main() {
    let tests = 1; // parse_line!(usize);
    for _ in 0..tests {
        solve();
    }
}


#[allow(unused_imports)]
use std::io::{stdin, Read, StdinLock};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::str::FromStr;
#[allow(unused_imports)]
use std::collections::{HashSet, HashMap, BinaryHeap};
#[allow(unused_imports)]
use std::vec::Vec;

#[allow(dead_code)]
const INF: i32 = 1000_000_000;
#[allow(dead_code)]
const INFLL: i64 = 1000_000_000_000_000_000;
#[allow(dead_code)]
const EPS: f64 = 1.0e-10;
#[allow(dead_code)]
const MOD: i32 = 1000_000_007;

struct Scanner<'a> {
    cin: StdinLock<'a>,
}

impl<'a> Scanner<'a> {
    #[allow(dead_code)]
    fn new(cin: StdinLock<'a>) -> Scanner<'a> {
        Scanner {cin: cin}
    }

    #[allow(dead_code)]
    fn read1<T: FromStr>(&mut self) -> Option<T> {
        let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
                    .skip_while(|c| c.is_whitespace())
                    .take_while(|c| !c.is_whitespace())
                    .collect::<String>();
        token.parse::<T>().ok()
    }

    #[allow(dead_code)]
    fn read<T: FromStr>(&mut self) -> T {
        self.read1().unwrap()
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin);

    let a: i32 = sc.read();
    let x: i32 = sc.read();
    let y: i32 = sc.read();
    let x = 2 * x;
    let y = 2 * y;
    let a = 2 * a;
    let mut ans = -1;
    if y % a != 0 {
        if 0 < y && y < a {
            if -a / 2 < x && x < a / 2 {
                ans = 1;
            }
        } else {
            let j = (y - a) / a;
            if j % 2 == 0 {
                if -a / 2 < x && x < a / 2 {
                    ans = 3 * j / 2 + 2;
                }
            } else {
                if -a < x && x < 0 {
                    ans = 3 * (j + 1) / 2;
                } else if 0 < x && x < a {
                    ans = 3 * (j + 1) / 2 + 1;
                }
            }
        }
    }

    println!("{}", ans);
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

fn gcd(mut a: usize, mut b: usize) -> usize {
    if b > a {
        std::mem::swap(&mut a, &mut b);
    }
    while b != 0 {
        let new_b = a % b;
        a = b;
        b = new_b;
    }
    if a == 0 {
        1
    } else {
        a
    }
}

fn _main() {
    let mut scan = Scan::new();
    let a: usize = scan.next();
    let b: usize = scan.next();
    let x = 6 - a.max(b) + 1;
    let common = gcd(x, 6);
    println!("{}/{}", x / common, 6 / common);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


use std::io;

fn read_line() -> String {
    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line).unwrap();
    return String::from(input_line.trim());
}

fn read_line_vec() -> Vec<u8> {
    return read_line().split(' ')
        .map(|s| s.parse().unwrap())
        .collect();
}

fn read_line_pair() -> (u8, u8) {
    let vec = read_line_vec();
    return (vec[0], vec[1]);
}

fn main() {
    let (a, b) = read_line_pair();
    let c = 6 - std::cmp::max(a, b) + 1;
    match c {
        2 => println!("1/3"),
        3 => println!("1/2"),
        4 => println!("2/3"),
        6 => println!("1/1"),
        _ => println!("{}/6", c)
    }
}


fn main() {
    let mut reader = scanner::TokenReader::new();
    let (a, b) = (reader.next::<u32>(), reader.next::<u32>());

    println!(
        "{}",
        ["", "1/1", "5/6", "2/3", "1/2", "1/3", "1/6"][std::cmp::max(a, b) as usize]
    );
}

// ---------- Begin Scanner ----------
#[allow(dead_code)]
mod scanner {
    use std::fmt::Debug;
    use std::str::FromStr;

    pub struct TokenReader {
        reader: std::io::Stdin,
        tokens: Vec<String>,
        index: usize,
    }

    impl TokenReader {
        pub fn new() -> Self {
            Self {
                reader: std::io::stdin(),
                tokens: Vec::new(),
                index: 0,
            }
        }

        pub fn next<T>(&mut self) -> T
        where
            T: FromStr,
            T::Err: Debug,
        {
            if self.index >= self.tokens.len() {
                self.load_next_line();
            }
            self.index += 1;
            self.tokens[self.index - 1].parse().unwrap()
        }

        pub fn vector<T>(&mut self) -> Vec<T>
        where
            T: FromStr,
            T::Err: Debug,
        {
            if self.index >= self.tokens.len() {
                self.load_next_line();
            }
            self.index = self.tokens.len();
            self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()
        }

        pub fn load_next_line(&mut self) {
            let mut line = String::new();
            self.reader.read_line(&mut line).unwrap();

            self.tokens = line.split_whitespace().map(String::from).collect();
            self.index = 0;
        }
    }
}
// ---------- End Scanner ----------


//! http://codeforces.com/contest/9/problem/A

fn main() {
  use std::io;
  let mut buf = String::new();
  io::stdin().read_line(&mut buf).unwrap();
  let mut ns = buf.split(" ")
    .map(|str| str.trim().parse::<u32>().unwrap());
  let y = ns.next().unwrap();
  let w = ns.next().unwrap();
  let r = std::cmp::max(y, w);
  println!("{}",
    match (6 - r) + 1 {
      1 => "1/6",
      2 => "1/3",
      3 => "1/2",
      4 => "2/3",
      5 => "5/6",
      6 => "1/1",
      _ => unreachable!()
    }
  );
}


use std::io;
use std::str::FromStr;

fn get_nums() -> Vec<i32> {
	let mut input = String::new();

	io::stdin().read_line(&mut input)
		.expect("");

	input.trim()
		.split_whitespace()
		.map(|d| i32::from_str(d).unwrap())
		.collect::<Vec<_>>()
}

fn get_pair() -> (i32, i32) {
	let v = get_nums();

	(v[0], v[1])
}

fn gcd(x: i32, y: i32) -> i32 {
	if y == 0 {
		x
	} else {
		gcd(y, x%y)
	}
}

fn main() {
	let (y, w) = get_pair();

	let m = if y > w  { y }  else { w };
	let c = 7-m;
	let g = gcd(c, 6);

	println!("{}/{}", c/g, 6/g);
}


// This code is licensed under the terms of Apache-2.0 <http://www.apache.org/licenses/LICENSE-2.0> or MIT License <https://opensource.org/licenses/MIT>, at your choice.

use crate::comprog_lib::scanner::Scanner;
use std::io::{self, Read, Write};
pub fn solve<R: Read, W: Write>(read: R, out: &mut W) -> io::Result<()> {
	let mut sc = Scanner::from(read);
	let n = sc.usize();
	let s = sc.token();
	let mut dp = vec![vec![std::i32::MAX; n + 1]; n + 1];
	for i in 0..=n {
		dp[i][i] = 0;
	}
	for len in 1..=n {
		for l in 0..=n - len {
			let r = l + len;
			dp[l][r] = std::iter::once(1 + dp[l + 1][r])
				.chain((l + 1..r).filter(|&i| s[l] == s[i]).map(|i| dp[l + 1][i] + dp[i][r]))
				.min()
				.unwrap();
		}
	}
	let ans = dp[0][n]; //assert_eq!(ans, naive(&s));
	writeln!(out, "{}", ans)?;
	Ok(())
}
fn main() {
	let stdin = io::stdin();
	let mut stdout = io::BufWriter::new(io::stdout());
	solve(stdin.lock(), &mut stdout).unwrap();
}
mod comprog_lib {
	// comprog_lib-0.1.0
	pub mod scan_buf {
		use std::io::{self, Read};
		#[derive(Debug, Clone)]
		pub struct ScanBuf {
			buf: Vec<u8>,
			pos: usize,
			end: usize,
		}
		#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
		pub struct ScanRange(pub usize, pub usize);
		impl ScanRange {
			pub fn slice(self, buf: &ScanBuf) -> &[u8] {
				&buf.buf[self.0..self.1]
			}
		}
		impl ScanBuf {
			pub fn new(initial_capacity: usize) -> Self {
				ScanBuf { buf: vec![0; initial_capacity], pos: 0, end: 0 }
			}
			pub fn scan<R: Read, P: FnMut(u8) -> bool>(
				&mut self,
				mut reader: R,
				mut pred: P,
			) -> io::Result<ScanRange> {
				let start = self.pos;
				loop {
					if self.pos >= self.end {
						if self.pos >= self.buf.len() {
							let new_len = std::cmp::max(self.buf.len(), 1) * 2;
							self.buf.resize(new_len, 0);
						}
						self.end += match reader.read(&mut self.buf[self.pos..]) {
							Ok(0) => return Ok(ScanRange(start, self.pos)),
							Ok(n) => n,
							Err(ref e) if e.kind() == io::ErrorKind::Interrupted => 0,
							Err(e) => return Err(e),
						};
					}
					assert!(self.end <= self.buf.len());
					while self.pos < self.end {
						if pred(self.buf[self.pos]) {
							return Ok(ScanRange(start, self.pos));
						}
						self.pos += 1;
					}
				}
			}
		}
	}
	pub mod scanner {
		use crate::comprog_lib::scan_buf::{ScanBuf, ScanRange};
		use std::io::Read;
		#[derive(Debug, Clone)]
		pub struct Scanner<R> {
			pub reader: R,
			pub buf: ScanBuf,
		}
		impl<R: Read> From<R> for Scanner<R> {
			fn from(r: R) -> Self {
				Scanner { reader: r, buf: ScanBuf::new(8192) }
			}
		}
		impl<R: Read> Scanner<R> {
			pub fn scan<P: FnMut(u8) -> bool>(&mut self, pred: P) -> ScanRange {
				self.buf.scan(&mut self.reader, pred).unwrap()
			}
			fn digits(&mut self) -> (bool, &[u8]) {
				self.scan(|b| b' ' < b);
				let mut negative = false;
				self.scan(|b| b != b'-' || std::mem::replace(&mut negative, true));
				let digits = self.scan(|b| b < b'0' || b'9' < b);
				(negative, digits.slice(&self.buf))
			}
			pub fn token_range(&mut self) -> ScanRange {
				self.scan(|b| b' ' < b);
				self.scan(|b| b <= b' ')
			}
			pub fn token(&mut self) -> Vec<u8> {
				self.token_range().slice(&self.buf).to_owned()
			}
		}
		macro_rules! impl_scan_int { ($($name:ident),*) => { impl<R: Read> Scanner<R> { $(       #[allow(unused)] pub fn $name(&mut self) -> $name { let (neg, digits) = self.digits(); if !neg { digits.iter().fold($name::default(), |x, b| x * 10 + $name::from(b - b'0')) } else { digits.iter().fold($name::default(), |x, b| x * 10 - $name::from(b - b'0')) } } )* } } }
		impl_scan_int!(u32, i32, u64, i64, usize);
	}
}
// Module comprog_lib contains code from comprog_lib <https://github.com/pcpthm/comprog_lib> licensed under Apache-2.0 OR MIT
// Built by comprog-0.1.0 <https://github.com/pcpthm/comprog_tools>


// This code is licensed under the terms of Apache-2.0 <http://www.apache.org/licenses/LICENSE-2.0> or MIT License <https://opensource.org/licenses/MIT>, at your choice.

use crate::comprog_lib::scanner::Scanner;
use std::cmp::min;
use std::io::{self, Read, Write};
pub fn solve<R: Read, W: Write>(read: R, out: &mut W) -> io::Result<()> {
    let mut sc = Scanner::from(read);
    let n = sc.usize();
    let s = sc.token();
    let mut next = vec![[n; 26]; n + 1];
    for i in (0..n).rev() {
        next[i] = next[i + 1].clone();
        next[i][(s[i] - b'a') as usize] = i;
    }
    #[allow(non_snake_case)]
    let INF = std::i32::MAX;
    let mut dp = vec![vec![INF; n + 1]; n + 1];
    let mut dp2 = vec![vec![[INF; 26]; n + 1]; n + 1];
    for i in 0..=n {
        dp[i][i] = 0;
        for a in 0..26 {
            dp2[i][i][a] = 0;
        }
    }
    for len in 1..=n {
        for l in 0..=n - len {
            let r = l + len;
            for a in 0..26 {
                let mut x = len as i32;
                if (s[r - 1] - b'a') as usize == a {
                    x = min(x, dp2[l][r - 1][a]);
                }
                for k in l + 1..r {
                    x = min(x, dp2[l][k][a] + dp[k][r]);
                }
                dp2[l][r][a] = x;
            }
            dp[l][r] = dp2[l][r].iter().cloned().min().unwrap() + 1;
        }
    }
    let ans = dp[0][n];
    writeln!(out, "{}", ans)?;
    Ok(())
}
fn main() {
    let stdin = io::stdin();
    let mut stdout = io::BufWriter::new(io::stdout());
    solve(stdin.lock(), &mut stdout).unwrap();
}
mod comprog_lib {
    // comprog_lib-0.1.0
    pub mod scan_buf {
        use std::io::{self, Read};
        #[derive(Debug, Clone)]
        pub struct ScanBuf {
            buf: Vec<u8>,
            pos: usize,
            end: usize,
        }
        #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
        pub struct ScanRange(pub usize, pub usize);
        impl ScanRange {
            pub fn slice(self, buf: &ScanBuf) -> &[u8] {
                &buf.buf[self.0..self.1]
            }
        }
        impl ScanBuf {
            pub fn new(initial_capacity: usize) -> Self {
                ScanBuf {
                    buf: vec![0; initial_capacity],
                    pos: 0,
                    end: 0,
                }
            }
            pub fn scan<R: Read, P: FnMut(u8) -> bool>(
                &mut self,
                mut reader: R,
                mut pred: P,
            ) -> io::Result<ScanRange> {
                let start = self.pos;
                loop {
                    if self.pos >= self.end {
                        if self.pos >= self.buf.len() {
                            let new_len = std::cmp::max(self.buf.len(), 1) * 2;
                            self.buf.resize(new_len, 0);
                        }
                        self.end += match reader.read(&mut self.buf[self.pos..]) {
                            Ok(0) => return Ok(ScanRange(start, self.pos)),
                            Ok(n) => n,
                            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => 0,
                            Err(e) => return Err(e),
                        };
                    }
                    assert!(self.end <= self.buf.len());
                    while self.pos < self.end {
                        if pred(self.buf[self.pos]) {
                            return Ok(ScanRange(start, self.pos));
                        }
                        self.pos += 1;
                    }
                }
            }
        }
    }
    pub mod scanner {
        use crate::comprog_lib::scan_buf::{ScanBuf, ScanRange};
        use std::io::Read;
        #[derive(Debug, Clone)]
        pub struct Scanner<R> {
            pub reader: R,
            pub buf: ScanBuf,
        }
        impl<R: Read> From<R> for Scanner<R> {
            fn from(r: R) -> Self {
                Scanner {
                    reader: r,
                    buf: ScanBuf::new(8192),
                }
            }
        }
        impl<R: Read> Scanner<R> {
            pub fn scan<P: FnMut(u8) -> bool>(&mut self, pred: P) -> ScanRange {
                self.buf.scan(&mut self.reader, pred).unwrap()
            }
            fn digits(&mut self) -> (bool, &[u8]) {
                self.scan(|b| b' ' < b);
                let mut negative = false;
                self.scan(|b| b != b'-' || std::mem::replace(&mut negative, true));
                let digits = self.scan(|b| b < b'0' || b'9' < b);
                (negative, digits.slice(&self.buf))
            }
            pub fn token_range(&mut self) -> ScanRange {
                self.scan(|b| b' ' < b);
                self.scan(|b| b <= b' ')
            }
            pub fn token(&mut self) -> Vec<u8> {
                self.token_range().slice(&self.buf).to_owned()
            }
        }
        macro_rules! impl_scan_int { ($($name:ident),*) => { impl<R: Read> Scanner<R> { $(       #[allow(unused)] pub fn $name(&mut self) -> $name { let (neg, digits) = self.digits(); if !neg { digits.iter().fold($name::default(), |x, b| x * 10 + $name::from(b - b'0')) } else { digits.iter().fold($name::default(), |x, b| x * 10 - $name::from(b - b'0')) } } )* } } }
        impl_scan_int!(u32, i32, u64, i64, usize);
    }
}
// Module comprog_lib contains code from comprog_lib <https://github.com/pcpthm/comprog_lib> licensed under Apache-2.0 OR MIT
// Built by comprog-0.1.0 <https://github.com/pcpthm/comprog_tools>


use std::io::Read;

fn run() {
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut it = s.trim().split_whitespace();
    let n: usize = it.next().unwrap().parse().unwrap();
    let s: Vec<char> = it.next().unwrap().chars().collect();
    let mut dp = vec![vec![0; n]; n];
    for len in 1..=n {
        for l in 0..=(n - len) {
            let r = l + len - 1;
            dp[l][r] = len;
            if l + 1 < n {
                dp[l][r] = dp[l + 1][r] + 1;
            }
            for k in (l + 1)..=r {
                if s[l] == s[k] {
                    dp[l][r] = std::cmp::min(dp[l][r], dp[l + 1][k - 1] + dp[k][r]);
                }
            }
        }
    }
    println!("{}", dp[0][n - 1]);
}

fn main() {
    run();
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! vec_dim {
	([$d:expr]$($s:tt)+) => {vec![vec_dim!($($s)+);$d]}; (=$e:expr) => {$e};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

fn rec(l: usize, r: usize, s: &[u8], memo: &mut [Vec<Option<usize>>]) -> usize {
	if l > r { return 0; }
	if let Some(res) = memo[l][r] {
		return res;
	}
	let mut res = r-l+1;
	for i in l+1..=r {
		m!(<, res, rec(l,i-1,s,memo) + rec(i,r,s,memo));
		if s[l] == s[i] {
			m!(<, res, rec(l+1,i-1,s,memo) + rec(i,r,s,memo));
		}
	}
	memo[l][r].replace(res);
	res
}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	let n = rin.u();
	let s = rin.vb();
	let mut dp = vec_dim!([n][n] = None);
	for i in 0..n {
		dp[i][i].replace(1);
	}
	let sol = rec(0, n-1, &s, &mut dp);
	writeln!(rout, "{}", sol).ok();
}


fn main() {
    let mut sin = ReadIn::new();
    let a = sin.intvec();
    let s: i32 = a.iter().sum();
    let x = (0..64).any(|b| if count(b) != 3 { false } else {
        (0..6)
            .filter_map(|i| if b & (1 << i) != 0 { Some(a[i as usize]) } else { None })
            .sum::<i32>() * 2 == s
    });
    println!("{}", if x {"YES"} else {"NO"});
}

fn count(i: i32) -> i32 {
    if i == 0 { 0 } else { 1 + count(i & (i - 1)) }
}

use std::iter::*;
use std::str::SplitWhitespace;
use std::io::stdin;
use std::mem::forget;

pub struct ReadIn(pub String);

impl ReadIn {
    pub fn new() -> ReadIn { ReadIn(String::new()) }
    fn read_i32(s: &str) -> i32 { s.parse().unwrap() }
    pub fn read_line(&mut self) {
        self.0.clear();
        forget(stdin().read_line(&mut self.0));
    }
    pub fn ints(&mut self) -> Map<SplitWhitespace, fn(&str) -> i32> {
        self.read_line();
        self.0.split_whitespace().map(ReadIn::read_i32)
    }
    pub fn intvec(&mut self) -> Vec<i32> { self.ints().collect() }
    pub fn int(&mut self) -> i32 { self.ints().next().unwrap() }
    pub fn int2(&mut self) -> (i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap())
    }

    pub fn int3(&mut self) -> (i32, i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())
    }
    pub fn int4(&mut self) -> (i32, i32, i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap(), it.next().unwrap(), it.next().unwrap())
    }
}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, BinaryHeap, VecDeque};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::stdin;

mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;

    #[allow(dead_code)]
    pub fn line() -> String {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    }

    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }
}

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

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn main() {
    let a = get!(usize;;);

    for p in 0usize..1 << 6 {
        if p.count_ones() != 3 {
            continue;
        }

        let mut x = 0;
        let mut y = 0;

        for k in 0..6 {
            if (p >> k) & 1 == 1 {
                x += a[k];
            } else {
                y += a[k];
            }
        }
        if x == y {
            println!("YES");
            return;
        }
    }
    println!("NO");
}


use std::io;
fn main(){
    let mut s=String::new();
    let mut c:usize=0;
    let mut a:Vec<i32>=Vec::new();
    let mut b:Vec<i32>=Vec::new();
    let mut n:usize=0;
    let mut sum:i32=0;
    let mut p:usize=0;
    io::stdin().read_line(&mut s).unwrap();
    s.trim();
    while c<s.len()-1{
        n=c;
        if s.chars().nth(c).unwrap()!=' '{
            while s.chars().nth(n+1).unwrap()!=' ' && n<s.len()-2{
                n+=1;
            }
            a.push(s[c..n+1].trim().to_string().parse().unwrap());
            sum+=a[p];
            p+=1;
            c=n;
        }
        c+=1;
    }
    n=0;
    for c in 0..6{
        for i in c+1..6{
            for q in i+1..6{
                if sum==2*(a[c]+a[i]+a[q]){
                    n+=1;
                }
            }
        }
    }
    if n>0{println!("YES")}
    else{println!("NO")}
}


fn read_line(mut buffer: &mut String) -> Vec<usize> {
    std::io::stdin().read_line(&mut buffer).expect("Error while reading input.");
    let data = buffer.split_whitespace().map(|x| x.parse::<usize>().unwrap()).collect();
    buffer.clear();
    data
}

fn get_index(i: usize, n: usize) -> String {
    let bin_str = format!("{:0width$b}", i, width = n);
    bin_str
}

fn limit(n: usize) -> usize {
    let mut n_bin = String::with_capacity(n);
    for _i in 0..n {
        n_bin.push('1');
    }
    let limit = usize::from_str_radix(&n_bin, 2).unwrap();
    limit
}
fn calculate(index: &String, c: &Vec<usize>, min: usize, max: usize, diff: usize) -> usize {
    let mut sum = 0;
    let mut cmin = 10_usize.pow(6) + 1;
    let mut cmax = 0;
    for (i, ch) in index.chars().enumerate() {
       if ch == '1' {
            if c[i] > cmax {
                cmax = c[i];
            }
            if c[i] < cmin {
                cmin = c[i];
            }
            sum += c[i];
       }
    }
    // need to find min and max
    if sum >= min && sum <= max && (cmax - cmin) >= diff {
       return 1
    }
    0
}

fn get_count(index: &String) -> usize {
    let mut count = 0;
    for ch in index.split("") {
        if ch == "1" {
            count += 1;
        }
    }
    count
}

fn main() {
    let mut buffer = String::new();

    let d = read_line(&mut buffer);
    //println!("D: {:?}", d);

    let (n, min, max, diff) = (d[0], d[1], d[2], d[3]);

    let c = read_line(&mut buffer);
    //println!("c: {:?}", c);

    let limit = limit(n);
    let mut result = 0;

    for i in 1..=limit {
        let index = get_index(i, n);
        let count = get_count(&index);
        if count > 1 {
            //println!("{:?}", index);
            let res = calculate(&index, &c, min, max, diff);
            if res == 1 {
                //println!("now");
            }
            result += res;
        }
    }
    println!("{}", result);
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! min {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! max {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! v {
	([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};
	([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: v!([]), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = v!([8]);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn board(&mut self, r: usize, c: Option<usize>) -> Vec<Vec<u8>> {
		let mut res = v!([r]);
		let c = c.unwrap_or(0);
		rep!{[r]
			let t = self.vb();
			assert!(c == 0 || t.len() == c);
			res.push(t);
		}
		res
	}
	fn framed_board(&mut self, r: usize, c: usize, f: u8) -> Vec<Vec<u8>> {
		let mut res = v!([r+2]);
		res.push( v!([c+2] = f) );
		rep!{[r]
			let mut t = self.vb();
			assert!(t.len() == c);
			t.reserve(2);
			t.insert(0,f);
			t.push(f);
			res.push(t);
		}
		res.push( v!([c+2] = f) );
		res
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
	fn graph(&mut self, n: usize, m: usize) -> Vec<Vec<usize>> {
		let mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e
	}
	fn graph_w<T: Copy+FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<(usize,T)>> where T::Err: Debug {
		let mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	let b = rin.l();
	let s = rin.vb();
	let n = s.len();
	let mut dp = v!([n+1] = std::i64::MAX);
	dp[0] = 0;
	for i in 0..n {
		let mut x = 0;
		for j in i..n {
			x = x * 10 + (s[j] - b'0') as i64;
			if (s[i] == b'0' && j > i) || x >= b {
				break;
			}
			min!(dp[j+1], dp[i].saturating_mul(b).saturating_add(x));
		}
	}
	writeln!(rout, "{}", dp[n]).ok();
}


macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

fn solve() {
    let n = parse_line!(u64);
    let s: Vec<_> = parse_line!(String).bytes().map(|c| (c - b'0') as u64).collect();
    let l = s.len();
    let mut dp = vec![std::u64::MAX; l + 1];
    dp[0] = 0;
    let mut digits = vec![0; l + 1];
    for (i, &c) in s.iter().enumerate() {
        for j in (1..=i + 1).rev() {
            digits[j] = digits[j - 1] * 10 + c;
        }
        for j in 0..=i {
            if digits[j + 1] >= n {
                break;
            }
            if j > 0 && s[i - j] == 0 {
                continue;
            }
            dp[i + 1] = std::cmp::min(dp[i + 1], dp[i - j] * n + digits[j + 1]);
        }
    }
    println!("{}", dp[l]);
}

fn main() {
    let tests = 1; // parse_line!(usize);
    for _ in 0..tests {
        solve();
    }
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::*;
#[allow(dead_code)]
fn getline() -> String {
    let mut ret = String::new();
    std::io::stdin().read_line(&mut ret).ok();
    return ret;
}
fn get_word() -> String {
    let mut stdin = std::io::stdin();
    let mut u8b: [u8; 1] = [0];
    loop {
        let mut buf: Vec<u8> = Vec::with_capacity(16);
        loop {
            let res = stdin.read(&mut u8b);
            if res.is_err() || res.ok().unwrap() == 0 || u8b[0] <= ' ' as u8 {
                break;
            } else {
                buf.push(u8b[0]);
            }
        }
        if buf.len() >= 1 {
            let ret = std::string::String::from_utf8(buf).unwrap();
            return ret;
        }
    }
}
fn parse<T: std::str::FromStr>(s: &str) -> T { s.parse::<T>().ok().unwrap() }

#[allow(dead_code)]
fn get<T: std::str::FromStr>() -> T { parse(&get_word()) }

fn numero(v: &[i64], b: i64) -> Option<i64> {
    let mut cur: i64 = 0;
    for &t in v.iter() {
        cur = match cur.checked_mul(b) {
            Some(v) => v,
            None => return None,
        };
        cur = match cur.checked_add(t) {
            Some(v) => v,
            None => return None,
        }
    }
    Some(cur)
}

fn checked_propagate(b: i64, x: i64, y: i64) -> Option<i64> {
    let cur = match x.checked_mul(b) {
        Some(v) => v,
        None => return None,
    };
    cur.checked_add(y)
}

fn main() {
    let b: i64 = get();
    let s: Vec<_> = get_word().bytes().map(|b| b as i64 - 0x30).collect();
    let n = s.len();
    if b <= 9 {
        // simply read b-base rep.
        let mut cur = 0;
        for v in s {
            cur *= b;
            cur += v;
        }
        println!("{}", cur);
        return;
    }
    let mut dp = vec![-1i64; n + 1];
    const INF: i64 = 1i64 << 60;
    dp[0] = 0;
    for i in 1 .. n + 1 {
        let mut mi = INF;
        for j in 1 .. i + 1 {
            // s[i - j ..i] < b ?
            if j >= 10 || dp[i - j] < 0 || (j >= 2 && s[i - j] == 0) {
                continue;
            }
            let sl = numero(&s[i - j .. i], 10);
            match sl {
                Some(v) if v < b => match checked_propagate(b, dp[i - j], v) {
                    Some(v) => { mi = min(mi, v) },
                    None => {},
                },
                _ => {},
            }
        }
        if mi < INF {
            dp[i] = mi;
        }
    }
    //println!("{:?}", dp);
    println!("{}", dp[n]);
}


use std::io::*;
use std::str::FromStr;

fn main() {
    let stdin = stdin();
    let mut sc = Scanner::new(stdin.lock());
    let n = sc.next::<i64>();
    let m = sc.next::<i64>();
    let k = sc.next::<i64>();

    if k < n {
        println!("{} 1", k + 1);
        return;
    }
    let y = n - (k - n) / (m - 1);
    let r = (k - n) % (m - 1);
    let x = if y % 2 == 0 { 2 + r } else { m - r };
    println!("{} {}", y, x);
}

// k < n なら1列目
// n < k なら snake 移動の途中
// 下から (n - k) / (m - 1)

pub struct Scanner<B> {
    reader: B,
    buffer: Vec<String>,
}

impl<B: BufRead> Scanner<B> {
    pub fn new(reader: B) -> Self {
        Self {
            reader,
            buffer: Vec::new(),
        }
    }

    pub fn next<T: FromStr>(&mut self) -> T
    where
        T::Err: ::std::fmt::Debug,
    {
        if let Some(front) = self.buffer.pop() {
            front.parse::<T>().expect(&front)
        } else {
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Line not read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
            self.next()
        }
    }
}


// Try Codeforces
// author: Leonardone @ NEETSDKASU

fn solve(n: i64, m: i64, k: i64) -> (i64, i64) {

    if k < n {
        return (k + 1, 1);
    }

    let e = k - n;
    let r = e / (m - 1);
    let c = e % (m - 1);

    let y = n - r;
    let x = if r % 2 == 0 { c + 2 } else { m - c };

    return (y, x);
}

fn main() {
    let mut stdin = String::new();
    std::io::Read::read_to_string(
        &mut std::io::stdin(),
        &mut stdin).unwrap();
    let mut stdin = stdin.split_whitespace();
    let mut get = || stdin.next().unwrap();
    macro_rules! get {
        ($t:ty) => (get().parse::<$t>().unwrap());
        () => (get!(i64));
    }

    let n = get!();
    let m = get!();
    let k = get!();

    if n * m < 20 {
        for e in 0..n*m {
            let (row, col) = solve(n, m, e);
            let (r, c) = brute_force(n, m, e);
            if row != r || col != c {
                //println!("error {} {} {}", n, m, e);
                //println!("solve {} {}", row, col);
                //println!("bf    {} {}", r, c);
                //panic!();
                break;
            }
        }
    }

    let (row, col) = solve(n, m, k);

    println!("{} {}", row, col);

}

fn brute_force(n: i64, m: i64, k: i64) -> (i64, i64) {
    let mut row = 1;
    let mut col = 1;
    let mut rem = k;

    if rem == 0 {
        return (row, col);
    }

    for _ in 0..n-1 {
        row += 1;
        rem -= 1;
        if rem == 0 {
            return (row, col);
        }
    }

    let mut state = 0;
    for _ in 0..rem {
        match state {
        0 => {
            col += 1;
            if col == m {
                state += 1;
            }
        },
        2 => {
            col -= 1;
            if col == 2 {
                state += 1;
            }
        },
        _ => {
            row -= 1;
            state = (state + 1) % 4;
        },
        }
    }
    return (row, col);
}


use std::collections::BinaryHeap;
use std::io;

fn get_line() -> io::Result<String> {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf)?;
    Ok(buf)
}

fn main() -> io::Result<()> {
    get_line()?;
    let buf = get_line()?;
    let mut iter = buf.split_ascii_whitespace().map(|x| x.parse().unwrap());

    let init = iter.next().unwrap();
    let a: Vec<u32> = iter.collect();

    let mut heap = BinaryHeap::from(a);
    let mut ans = 0;

    while *heap.peek().unwrap() >= init + ans {
        let top = heap.pop().unwrap();
        heap.push(top - 1);
        ans += 1;
    }

    println!("{}", ans);

    Ok(())
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let line = self.next_line();
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

    fn next_n<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next()).collect()
    }
}

fn process(colors: &[u64], perm: &Vec<usize>) -> u64 {
    let mut result = 0u64;
    let mut lcolors = [0u64, 0, 0];
    lcolors.clone_from_slice(colors);
    for current in perm {
        if *current == 3 {
            let take = *lcolors.iter().min().unwrap();
            result += take;
            for i in &mut lcolors {
                *i -= take;
            }
            continue;
        }
        result += lcolors[*current] / 3;
        lcolors[*current] %= 3;
    }
    result
}

fn permutations(colors: &[u64], current: &mut Vec<usize>, step: usize, result: &mut u64) {
    if step == 4 {
        *result = (*result).max(process(colors, current));
        return;
    }
    for i in 0..4 {
        if let None = current.iter().find(|x| **x == i) {
            current.push(i);
            permutations(colors, current, step + 1, result);
            current.pop();
        }
    }
}

fn _main() {
    let mut scan = Scan::new();
    let colors: Vec<u64> = scan.next_n(3);
    let mut result = 0u64;
    let mut perm: Vec<usize> = vec![];
    permutations(&colors, &mut perm, 0, &mut result);
    println!("{}", result);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


fn read_string() -> String {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed");
    input
}

fn main(){

    let mut x = read_string();
    x = x.replace("\r", "");
    let vec: Vec<&str> = x.split("").collect();
    let mut found: bool =  false;
    for n in 2..(vec.len()-3){
        if ((vec[n] != ".") && (vec[n+1] != ".") && (vec[n-1] != ".")) &&
            ((vec[n] != vec[n+1]) && (vec[n-1] != vec[n+1]) && (vec[n] != vec[n-1]))
            {
            found = true;
            break
        }
    }
    println!("{}", if found {"YES"} else {"NO"});
}


use std::io;
use std::io::Stdin;

fn read_line(stdin : &Stdin, line : &mut String) {
    match stdin.read_line(line) {
        Ok(_) => return,
        Err(msg) => panic!("Could not read line! Message: {}.", msg),
    }
}

fn contains_3_colors(s : &String) -> bool {
    let contains_abc = s.contains("ABC");
    let contains_acb = s.contains("ACB");
    let contains_bac = s.contains("BAC");
    let contains_bca = s.contains("BCA");
    let contains_cab = s.contains("CAB");
    let contains_cba = s.contains("CBA");
    contains_abc || contains_acb ||
    contains_bac || contains_bca ||
    contains_cab || contains_cba
}

fn main() {
    let stdin = io::stdin();
    let mut s = String::new();
    read_line(&stdin, &mut s);
    if contains_3_colors(&s) {
        println!("Yes")
    } else {
        println!("No");
    }
}


use std::io;
use std::str::FromStr;

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

fn main() {
    let n: usize = get_line().trim().parse().unwrap();

    let mut input = String::new();
    use std::io::Read;
    io::stdin().read_to_string(&mut input).unwrap();

    let a: Vec<u8> = input.split_whitespace()
        .map(|x| x.parse().unwrap()).collect();

    let next = |winner, spec| {
        6 - winner - spec
    };

    let specs: Vec<_> = a.iter().scan(3, |state, winner| {
        let spec = *state;
        *state = next(winner, spec);
        Some(spec)
    }).collect();

    let ans = (0..n).all(|i| a[i] != specs[i]);

    if ans {
        println!("YES");
    } else {
        println!("NO");
    }
}

struct Solver {

}

impl Solver {

}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, BinaryHeap, VecDeque, BTreeSet, BTreeMap};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::stdin;

mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;

    #[allow(dead_code)]
    pub fn line() -> String {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    }

    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }
}

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

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn main() {
    let n = get!(usize);
    let games = get!(usize;n);

    let mut players = (1, 2);
    let mut spec = 3;

    for g in games {
        if g == players.0 {
            let t = spec;
            spec = players.1;
            players = (g, t);
        } else if g == players.1 {
            let t = spec;
            spec = players.0;
            players = (g, t);
        } else {
            println!("NO");
            return;
        }
    }

    println!("YES");
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

fn run() {
    input! {
        n: usize,
        a: [usize; n],
    }
    let mut x = 1;
    let mut y = 2;
    let mut z = 3;
    for a in a {
        if a == x {
            std::mem::swap(&mut y, &mut z);
        } else if a == y {
            std::mem::swap(&mut x, &mut z);
        } else {
            println!("NO");
            return;
        }
    }
    println!("YES");
}

fn main() {
    run();
}


use std::io::stdin;

fn main() {
    let mut input = String::new();
    stdin().read_line(&mut input).unwrap();
    let nk = input.split_whitespace().map(|x| x.parse::<i32>().unwrap()).collect::<Vec<_>>();
    let k = &nk[1];

    input.clear();
    stdin().read_line(&mut input).unwrap();
    let buckets = input.split_whitespace().map(|x| x.parse::<i32>().unwrap()).collect::<Vec<i32>>();

    let mut best_time = 100;
    for bucket in buckets {
        if k % bucket == 0 && k / bucket < best_time {
            best_time = k / bucket;
        }
    }
    println!("{}", best_time);
}


use std::io;

fn main() {
  let mut buffer = String::new();
  io::stdin().read_line(&mut buffer).unwrap();
  let k = buffer.split_whitespace()
                .map(|x| x.trim().parse::<u8>().unwrap())
                .last()
                .unwrap();
  buffer.clear();
  io::stdin().read_line(&mut buffer).unwrap();
  let bucket = buffer.split_whitespace()
                     .map(|x| x.trim().parse::<u8>().unwrap())
                     .filter(|x| k % x == 0)
                     .max()
                     .unwrap();

  println!("{}", k / bucket);
}


//spnauti-rusT
use std::io::*;
use std::str::{self,*};
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_macros)]
macro_rules! m {
    ($c:tt, $x:expr, $y:expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
#[allow(unused_macros)]
macro_rules! l {
    ($($v:ident),* = $i:ident.$f:ident $a:tt) => {
        $( let $v = $i.$f$a; )*
    };
    ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {
        $( let $v:$t = $i.$f$a; )*
    };
}
struct WordReader<'a> { it : SplitAsciiWhitespace<'a> }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).ok();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn f(&mut self) ->    f64 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn sk(&mut self, n: usize) { self.it.nth(n - 1); }
    fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> {
        self.ip(n).into_iter()
    }
    fn vi(&mut self, n: usize) -> Vec<i32> {
        self.vp::<i32>(n)
    }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
        self.vp(n).into_iter()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}
//------------------- End rusT

fn main() {
    let mut bin = String::new();
    let mut input = WordReader::from_stdin(&mut bin);

    let n = input.u();
    let k = input.i();
    let sol = k / input.ii(n).filter(|&x| k % x == 0).max().unwrap();
    println!("{}", sol);
}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::stdin;
mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;
    #[allow(dead_code)]
    pub fn line() -> String {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    }
    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }
}
#[allow(unused_macros)]
macro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = 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 < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }

fn main() {
    let (n, k) = get!(usize, usize);
    let aa = get!(usize;;);

    let ans = aa.iter()
        .filter_map(|&a| if k % a == 0 { Some(k / a) } else { None })
        .min()
        .unwrap();

    println!("{}", ans);
}


use std::io::*;

fn main () {
    let mut input = String::new();
    stdin().read_line(&mut input).expect("Can't read input\n");
    let inp = input
        .split_whitespace()
        .map(|s| s.parse()
        .expect("Can't parse input")).collect::<Vec<i32>>();
    let (n, k) = (inp[0], inp[1]);
    input.clear();
    stdin().read_line(&mut input).expect("Can't read input\n");
    let inp1 = input
        .split_whitespace()
        .map(|s| s.parse().expect("Can't parse input"))
        .collect::<Vec<i32>>();

    let h = inp1
        .into_iter()
        .map(|x| (k / x, k % x))
        .filter(|&(_, r)| r == 0)
        .min_by(|a, b| a.0.cmp(&b.0))
        .unwrap()
        .0;
    println!("{}", h);
}


use std::io;
fn main(){
    let mut s:String=String::new();
    io::stdin().read_line(&mut s).unwrap();
    let mut c:usize=0;
    let mut n:usize=0;
    let mut a:Vec<i32>=Vec::new();
    while c<s.len()-1{
        n=c;
        if s.chars().nth(c).unwrap()!=' '{
            while s.chars().nth(n).unwrap()!=' ' && n<s.len()-1{
                n+=1;
            }
            a.push(s[c..n].trim().to_string().parse().unwrap());
            c=n;
        }
        c+=1;
    }
    let a=a[1];
    let mut s:String=String::new();
    io::stdin().read_line(&mut s).unwrap();
    n=0;
    c=0;
    let mut b:Vec<i32>=Vec::new();
    while c<s.len()-1{
        n=c;
        if s.chars().nth(c).unwrap()!=' '{
            while s.chars().nth(n).unwrap()!=' ' && n<s.len()-1{
                n+=1;
            }
            b.push(s[c..n].trim().to_string().parse().unwrap());
            c=n;
        }
        c+=1;
    }
    let mut n:i32=a;
    for c in 0..b.len(){
        if n>a/b[c] && a%b[c]==0{
            n=a/b[c];
        }
    }
    println!("{}",n)
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let line = self.next_line();
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    println!(
        "{}",
        match n {
            11..=19 | 21 => {
                4
            }
            20 => {
                15
            }
            _ => {
                0
            }
        }
    );
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


fn main() {
    let mut input = String::new();
    use std::io::prelude::*;
    use std::io;
    io::stdin().read_to_string(&mut input).unwrap();

    let mut it = input.split_whitespace();

    let n: usize = it.next().unwrap().parse().unwrap();
    let d: i32 = it.next().unwrap().parse().unwrap();

    let mut cl: Vec<i32> = it.map(|x| x.parse().unwrap()).collect();

    cl.sort_unstable();

    for i in (1..n + 1).rev() {
        let p = cl.windows(i).any(|win| *win.last().unwrap() - *win.first().unwrap() <= d);
        if p {
            let ans = n - i;
            println!("{}", ans);
            return;
        }
    }
}


use std::io;
use std::cmp::max;
//use std::io::prelude::*;

fn main() {
    let nd = get_ints();
    let mut nums = get_ints();
    nums.sort();

    println!("{}", min_points(nd, nums));

}

fn min_points(nd : Vec<i32>, nums : Vec<i32>) -> i32 {
    let n = nd[0] as usize;
    let d = nd[1] ;

    let mut high : usize = 0;
    let mut ans : usize = 0;

    for  low in 0..n {
        while  high < n && nums[high] - nums[low] <= d {
            ans = max(ans, high - low);
            high += 1;
        }
    }

    (n-ans-1) as i32

}

fn get_ints() -> Vec<i32> {
    let mut input_text = String::new();
    io::stdin().read_line( &mut input_text )
               .expect( "could not read line" );
    let numbers : Vec<i32> = input_text.trim()
                                           .split_whitespace()
                                           .map(|x| x.parse::<i32>().unwrap())
                                           .collect();

    numbers
}


#![allow(unused_imports, unused_macros, dead_code)]
use std::f64::*;
use std::cmp::*;
use std::collections::*;

macro_rules! dump{
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

const INF: i64 = 0x3f3f3f3f3f3f3f3f;
const MOD: i64 = 1000000007;
const NOTHING: usize = std::usize::MAX;
const DX: [usize; 4] = [1, 0, std::usize::MAX, 0];
const DY: [usize; 4] = [0, 1, 0, std::usize::MAX];

fn main() {
    let (n, d): (usize, usize) = readln();
    let xs: Vec<usize> = readln();

    let mut res: usize = n;
    for l in 1..101 {
        let r = l + d;
        let mut cnt = 0;
        for &x in &xs {
            if x < l || r < x {
                cnt += 1;
            }
        }
        res = min(res, cnt);
    }
    println!("{}", res);
}

trait Read {
    fn read(s: &str) -> Self;
}

fn readln<T: Read>() -> T {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    T::read(buf.trim_right())
}

macro_rules! read_impl{
    ($($t:ty)*) => ($(
        impl Read for $t {
            fn read(s: &str) -> $t{
                s.parse().unwrap()
            }
        }
    )*)
}
read_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }

impl Read for String {
    fn read(s: &str) -> Self {
        s.to_string()
    }
}

impl Read for Vec<char> {
    fn read(s: &str) -> Self {
        s.chars().collect()
    }
}

impl<T: Read> Read for Vec<T> {
    fn read(s: &str) -> Self {
        s.split_whitespace().map(T::read).collect()
    }
}

impl<A: Read, B: Read> Read for (A, B) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]))
    }
}

impl<A: Read, B: Read, C: Read> Read for (A, B, C) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))
    }
}

impl<A: Read, B: Read, C: Read, D: Read> Read for (A, B, C, D) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]), D::read(tokens[3]))
    }
}