Problem:
Score : 500 points

Problem Statement

Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions:

A_i \neq B_i, for every i such that 1\leq i\leq N.

A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.

Since the count can be enormous, print it modulo (10^9+7).

Constraints

1\leq N \leq M \leq 5\times10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the count modulo (10^9+7).

Sample Input 1

2 2

Sample Output 1

2

A_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.

Sample Input 2

2 3

Sample Output 2

18

Sample Input 3

141421 356237

Sample Output 3

881613484

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

// This code is generated by [cargo-atcoder](https://github.com/tanakh/cargo-atcoder)
// Original source code:
/*
#![allow(unused_imports)]
#![allow(bare_trait_objects)] // for compatibility with 1.15.1
use std::cmp::Ordering::{self, Greater, Less};
use std::cmp::{max, min};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::error::Error;
use std::io::{self, BufReader, BufWriter, Read, Write};
use text_scanner::{scan, scan_iter, scanln, scanln_iter};
use utils::adj4_iter;

fn run() {
    let n: u64 = scan();
    let m: u64 = scan();
    let c: Comb<Mod107> = Comb::new(1_000_000);
    let left = c.perm(m, n);
    let mut right: Mint107 = 0.into();
    for i in 0..=n {
        if i % 2 == 0 {
            right += c.comb(n, i) * c.perm(m - i, n - i);
        } else {
            right -= c.comb(n, i) * c.perm(m - i, n - i);
        }
    }
    let ans = left * right;
    println!("{}", ans);
}

fn main() {
    std::thread::Builder::new()
        .name("run".to_string())
        .stack_size(256 * 1024 * 1024)
        .spawn(run)
        .unwrap()
        .join()
        .unwrap()
}
//{{{ utils
pub mod utils {
    static DY: [isize; 8] = [0, 1, 0, -1, 1, -1, 1, -1];
    static DX: [isize; 8] = [1, 0, -1, 0, 1, 1, -1, -1];

    fn try_adj(
        y: usize,
        x: usize,
        dy: isize,
        dx: isize,
        h: usize,
        w: usize,
    ) -> Option<(usize, usize)> {
        let ny = y as isize + dy;
        let nx = x as isize + dx;
        if ny >= 0 && nx >= 0 {
            let ny = ny as usize;
            let nx = nx as usize;
            if ny < h && nx < w {
                Some((ny, nx))
            } else {
                None
            }
        } else {
            None
        }
    }

    pub struct Adj4 {
        y: usize,
        x: usize,
        h: usize,
        w: usize,
        r: usize,
    }

    impl Iterator for Adj4 {
        type Item = (usize, usize);

        fn next(&mut self) -> Option<Self::Item> {
            loop {
                if self.r >= 4 {
                    return None;
                }

                let dy = DY[self.r];
                let dx = DX[self.r];
                self.r += 1;

                if let Some((ny, nx)) = try_adj(self.y, self.x, dy, dx, self.h, self.w) {
                    return Some((ny, nx));
                }
            }
        }
    }

    pub fn adj4_iter(y: usize, x: usize, h: usize, w: usize) -> Adj4 {
        Adj4 {
            y: y,
            x: x,
            h: h,
            w: w,
            r: 0,
        }
    }
}
pub mod text_scanner {
    use std;
    #[derive(Debug)]
    pub enum Error {
        IoError(std::io::Error),
        EncodingError(std::string::FromUtf8Error),
        ParseError(String),
        Eof,
    }

    impl std::fmt::Display for Error {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            match *self {
                Error::IoError(ref e) => writeln!(f, "IO Error: {}", e),
                Error::EncodingError(ref e) => writeln!(f, "Encoding Error: {}", e),
                Error::ParseError(ref e) => writeln!(f, "Parse Error: {}", e),
                Error::Eof => writeln!(f, "EOF"),
            }
        }
    }

    impl std::error::Error for Error {
        // dummy implementation for 1.15.1
        fn description(&self) -> &str {
            "description() is deprecated; use Display"
        }
    }

    pub fn read_line() -> Option<String> {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        fread_line(&mut stdin).expect("IO error")
    }

    pub fn scan<T: FromTokens>() -> T {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        fscan(&mut stdin).expect("IO error")
    }

    pub fn scanln<T: FromTokens>() -> T {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        fscanln(&mut stdin).expect("IO error")
    }

    pub fn scan_iter<T: FromTokens>() -> ScanIter<T> {
        ScanIter {
            item_type: std::marker::PhantomData,
        }
    }

    pub fn scanln_iter<T: FromTokens>() -> ScanlnIter<T> {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        let s = fread_line(&mut stdin)
            .expect("IO error")
            .unwrap_or_else(String::new);
        ScanlnIter {
            cursor: std::io::Cursor::new(s),
            item_type: std::marker::PhantomData,
        }
    }

    pub fn fread_line<R: std::io::BufRead>(r: &mut R) -> Result<Option<String>, std::io::Error> {
        let mut buf = String::new();
        let length = r.read_line(&mut buf)?;
        if let Some('\n') = buf.chars().last() {
            buf.pop();
        }
        if let Some('\r') = buf.chars().last() {
            buf.pop();
        }
        if length == 0 {
            Ok(None)
        } else {
            Ok(Some(buf))
        }
    }

    pub fn fscan<R: std::io::Read, T: FromTokens>(reader: &mut R) -> Result<T, Error> {
        let mut tokenizer = Tokenizer::new(reader);
        FromTokens::from_tokens(&mut tokenizer)
    }

    pub fn fscanln<R: std::io::BufRead, T: FromTokens>(reader: &mut R) -> Result<T, Error> {
        let s = match fread_line(reader) {
            Ok(Some(s)) => s,
            Ok(None) => return Err(Error::Eof),
            Err(e) => return Err(Error::IoError(e)),
        };
        let mut bytes = s.as_bytes();
        let mut tokenizer = Tokenizer::new(&mut bytes);
        FromTokens::from_tokens(&mut tokenizer)
    }

    pub fn fscan_iter<R: std::io::Read, T: FromTokens>(reader: &mut R) -> FscanIter<R, T> {
        FscanIter {
            tokenizer: Tokenizer::new(reader),
            item_type: std::marker::PhantomData,
        }
    }

    pub fn fscanln_iter<R: std::io::BufRead, T: FromTokens>(
        reader: &mut R,
    ) -> Result<ScanlnIter<T>, Error> {
        let s = match fread_line(reader) {
            Ok(Some(s)) => s,
            Ok(None) => "".to_string(),
            Err(e) => return Err(Error::IoError(e)),
        };
        Ok(ScanlnIter {
            cursor: std::io::Cursor::new(s),
            item_type: std::marker::PhantomData,
        })
    }

    pub struct ScanIter<T>
    where
        T: FromTokens,
    {
        item_type: std::marker::PhantomData<T>,
    }

    impl<T: FromTokens> Iterator for ScanIter<T> {
        type Item = T;

        fn next(&mut self) -> Option<Self::Item> {
            let stdin = std::io::stdin();
            let mut stdin = stdin.lock();
            let mut tokenizer = Tokenizer::new(&mut stdin);
            match FromTokens::from_tokens(&mut tokenizer) {
                Err(Error::Eof) => None,
                r => Some(r.expect("IO error")),
            }
        }
    }

    pub struct FscanIter<'a, R, T>
    where
        R: std::io::Read + 'a,
        T: FromTokens,
    {
        tokenizer: Tokenizer<'a, R>,
        item_type: std::marker::PhantomData<T>,
    }

    impl<'a, R: std::io::Read, T: FromTokens> Iterator for FscanIter<'a, R, T> {
        type Item = Result<T, Error>;

        fn next(&mut self) -> Option<Self::Item> {
            match FromTokens::from_tokens(&mut self.tokenizer) {
                Err(Error::Eof) => None,
                r => Some(r),
            }
        }
    }

    pub struct ScanlnIter<T>
    where
        T: FromTokens,
    {
        cursor: std::io::Cursor<String>,
        item_type: std::marker::PhantomData<T>,
    }

    impl<'a, T: FromTokens> Iterator for ScanlnIter<T> {
        type Item = T;

        fn next(&mut self) -> Option<Self::Item> {
            let mut tokenizer = Tokenizer::new(&mut self.cursor);
            match FromTokens::from_tokens(&mut tokenizer) {
                Err(Error::Eof) => None,
                r => Some(r.expect("IO error")),
            }
        }
    }

    pub trait FromTokens
    where
        Self: Sized,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error>;
    }

    macro_rules! from_tokens_primitives {
    ($($t:ty),*) => { $(
        impl FromTokens for $t {
            fn from_tokens(tokenizer: &mut Iterator<Item = Result<String, Error>>) -> Result<Self, Error> {
                let token = tokenizer.next();
                match token {
                    Some(s) => s?
                        .parse::<$t>()
                        .map_err(|e| Error::ParseError(format!("{}", e))),
                    None => Err(Error::Eof),
                }
            }
        }
    )* }
}

    from_tokens_primitives! {
        String,
        bool,
        f32,
        f64,
        isize,
        i8,
        i16,
        i32,
        i64,
        usize,
        u8,
        u16,
        u32,
        u64
    }

    impl FromTokens for Vec<char> {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok(String::from_tokens(tokenizer)?.chars().collect())
        }
    }

    impl<T1, T2> FromTokens for (T1, T2)
    where
        T1: FromTokens,
        T2: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((T1::from_tokens(tokenizer)?, T2::from_tokens(tokenizer)?))
        }
    }

    impl<T1, T2, T3> FromTokens for (T1, T2, T3)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
            ))
        }
    }

    impl<T1, T2, T3, T4> FromTokens for (T1, T2, T3, T4)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
        T4: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
                T4::from_tokens(tokenizer)?,
            ))
        }
    }

    impl<T1, T2, T3, T4, T5> FromTokens for (T1, T2, T3, T4, T5)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
        T4: FromTokens,
        T5: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
                T4::from_tokens(tokenizer)?,
                T5::from_tokens(tokenizer)?,
            ))
        }
    }

    impl<T1, T2, T3, T4, T5, T6> FromTokens for (T1, T2, T3, T4, T5, T6)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
        T4: FromTokens,
        T5: FromTokens,
        T6: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
                T4::from_tokens(tokenizer)?,
                T5::from_tokens(tokenizer)?,
                T6::from_tokens(tokenizer)?,
            ))
        }
    }

    struct Tokenizer<'a, R: std::io::Read + 'a> {
        reader: &'a mut R,
    }

    impl<'a, R: std::io::Read> Tokenizer<'a, R> {
        pub fn new(reader: &'a mut R) -> Self {
            Tokenizer { reader: reader }
        }

        pub fn next_token(&mut self) -> Result<Option<String>, Error> {
            use std::io::Read;
            let mut token = Vec::new();
            for b in self.reader.by_ref().bytes() {
                let b = b.map_err(Error::IoError)?;
                match (is_ascii_whitespace(b), token.is_empty()) {
                    (false, _) => token.push(b),
                    (true, false) => break,
                    (true, true) => {}
                }
            }
            if token.is_empty() {
                return Ok(None);
            }
            String::from_utf8(token)
                .map(Some)
                .map_err(Error::EncodingError)
        }
    }

    impl<'a, R: std::io::Read> Iterator for Tokenizer<'a, R> {
        type Item = Result<String, Error>;
        fn next(&mut self) -> Option<Self::Item> {
            match self.next_token() {
                Ok(Some(s)) => Some(Ok(s)),
                Ok(None) => None,
                Err(e) => Some(Err(e)),
            }
        }
    }

    fn is_ascii_whitespace(b: u8) -> bool {
        // Can use u8::is_ascii_whitespace once removing support of 1.15.1
        match b {
            b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
            _ => false,
        }
    }
}

pub trait SetMinMax {
    fn set_min(&mut self, v: Self) -> bool;
    fn set_max(&mut self, v: Self) -> bool;
}

impl<T> SetMinMax for T
where
    T: PartialOrd,
{
    fn set_min(&mut self, v: T) -> bool {
        *self > v && {
            *self = v;
            true
        }
    }
    fn set_max(&mut self, v: T) -> bool {
        *self < v && {
            *self = v;
            true
        }
    }
}

#[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
pub struct Reverse<T>(pub T);

impl<T: PartialOrd> PartialOrd for Reverse<T> {
    #[inline]
    fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }

    #[inline]
    fn lt(&self, other: &Self) -> bool {
        other.0 < self.0
    }
    #[inline]
    fn le(&self, other: &Self) -> bool {
        other.0 <= self.0
    }
    #[inline]
    fn ge(&self, other: &Self) -> bool {
        other.0 >= self.0
    }
    #[inline]
    fn gt(&self, other: &Self) -> bool {
        other.0 > self.0
    }
}

impl<T: Ord> Ord for Reverse<T> {
    #[inline]
    fn cmp(&self, other: &Reverse<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}

#[derive(PartialEq, PartialOrd, Debug, Copy, Clone, Default)]
pub struct Num(pub f64);

impl Eq for Num {}

impl Ord for Num {
    fn cmp(&self, other: &Num) -> Ordering {
        self.0
            .partial_cmp(&other.0)
            .expect("unexpected NaN when compare")
    }
}

// See https://docs.rs/superslice/1.0.0/superslice/trait.Ext.html
pub trait SliceExt {
    type Item;

    fn lower_bound(&self, x: &Self::Item) -> usize
    where
        Self::Item: Ord;

    fn lower_bound_by<'a, F>(&'a self, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering;

    fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord;

    fn upper_bound(&self, x: &Self::Item) -> usize
    where
        Self::Item: Ord;

    fn upper_bound_by<'a, F>(&'a self, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering;

    fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord;
}

impl<T> SliceExt for [T] {
    type Item = T;

    fn lower_bound(&self, x: &Self::Item) -> usize
    where
        T: Ord,
    {
        self.lower_bound_by(|y| y.cmp(x))
    }

    fn lower_bound_by<'a, F>(&'a self, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering,
    {
        let s = self;
        let mut size = s.len();
        if size == 0 {
            return 0;
        }
        let mut base = 0usize;
        while size > 1 {
            let half = size / 2;
            let mid = base + half;
            let cmp = f(unsafe { s.get_unchecked(mid) });
            base = if cmp == Less { mid } else { base };
            size -= half;
        }
        let cmp = f(unsafe { s.get_unchecked(base) });
        base + (cmp == Less) as usize
    }

    fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord,
    {
        self.lower_bound_by(|e| f(e).cmp(k))
    }

    fn upper_bound(&self, x: &Self::Item) -> usize
    where
        T: Ord,
    {
        self.upper_bound_by(|y| y.cmp(x))
    }

    fn upper_bound_by<'a, F>(&'a self, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering,
    {
        let s = self;
        let mut size = s.len();
        if size == 0 {
            return 0;
        }
        let mut base = 0usize;
        while size > 1 {
            let half = size / 2;
            let mid = base + half;
            let cmp = f(unsafe { s.get_unchecked(mid) });
            base = if cmp == Greater { base } else { mid };
            size -= half;
        }
        let cmp = f(unsafe { s.get_unchecked(base) });
        base + (cmp != Greater) as usize
    }

    fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord,
    {
        self.upper_bound_by(|e| f(e).cmp(k))
    }
}
//}}}
use std::fmt;
use std::marker::PhantomData;
use std::mem;
use std::ops;

/// Trait for `Mint`. `module()` should return prime number.
pub trait Module: Copy + Clone {
    fn module() -> u32;
}

/// One of famous numbers in programming contest. `10^9 + 7`
pub const MOD_107: u32 = 1_000_000_007;
/// One of famous numbers in programming contest. `10^9 + 9`
pub const MOD_109: u32 = 1_000_000_009;
/// One of famous numbers in programming contest. `998_244_353`
pub const MOD_998: u32 = 998_244_353;

/// struct to implement Module trait. it returns `MOD_107`.
#[derive(Debug, Copy, Clone)]
pub struct Mod107;
impl Module for Mod107 {
    fn module() -> u32 {
        MOD_107
    }
}

/// struct to implement Module trait. it returns `MOD_109`.
#[derive(Debug, Copy, Clone)]
pub struct Mod109;
impl Module for Mod109 {
    fn module() -> u32 {
        MOD_109
    }
}

/// struct to implement Module trait. it returns `MOD_998`.
#[derive(Debug, Copy, Clone)]
pub struct Mod998;
impl Module for Mod998 {
    fn module() -> u32 {
        MOD_998
    }
}

/// Wrapper class to compute mod `1_000_000_007` automatically.
///
/// # Examples
/// ```
/// use algorithms::math::{Mint107, MOD_107};
/// let x: Mint107 = 1234567.into();
/// let y: Mint107 = 2345678.into();
/// let z = x * y;
/// # // TODO: implement convert to u64
/// assert_eq!(z.val as u64, 1234567u64 * 2345678u64 % MOD_107 as u64);
/// ```
///
pub type Mint107 = Mint<Mod107>;

/// Wrapper class to compute mod `1_000_000_009` automatically.
///
/// # Examples
/// ```
/// use algorithms::math::{Mint109, MOD_109};
/// let x: Mint109 = 1234567.into();
/// let y: Mint109 = 2345678.into();
/// let z = x * y;
/// assert_eq!(z.val as u64, 1234567u64 * 2345678u64 % MOD_109 as u64);
/// ```
///
pub type Mint109 = Mint<Mod109>;

/// Wrapper class to compute mod `998_244_353` automatically.
///
/// # Examples
/// ```
/// use algorithms::math::{Mint998, MOD_998};
/// let x: Mint998 = 1234567.into();
/// let y: Mint998 = 2345678.into();
/// let z = x * y;
/// assert_eq!(z.val as u64, 1234567u64 * 2345678u64 % MOD_998 as u64);
/// ```
///
pub type Mint998 = Mint<Mod998>;

/// Wrapper class to compute modulo operation.
/// See examples
/// [`Mint107`](type.Mint107.html),
/// [`Mint109`](type.Mint109.html),
/// [`Mint998`](type.Mint998.html)
///
/// # Examples
/// ```
/// use algorithms::math::{Mint107, MOD_107};
/// let x: Mint107 = 1234567.into();
/// let y: Mint107 = 2345678.into();
/// let z = x * y;
/// assert_eq!(z.val as u64, 1234567u64 * 2345678u64 % MOD_107 as u64);
/// ```
#[derive(Debug, Copy, Clone, Eq)]
pub struct Mint<M: Module> {
    /// internal value. this is always less than `self.module()`.
    pub val: u32,
    m: PhantomData<M>,
}

impl<M: Module> Mint<M> {
    fn module(self) -> u32 {
        M::module()
    }
    fn new(val: u32) -> Mint<M> {
        assert!(val < M::module());
        Mint {
            val,
            m: PhantomData,
        }
    }
}

impl<T: Into<Mint<M>>, M: Module> ops::Add<T> for Mint<M> {
    type Output = Mint<M>;

    fn add(self, other: T) -> Mint<M> {
        let nval = self.val + other.into().val;
        Mint::new(if nval >= self.module() {
            nval - self.module()
        } else {
            nval
        })
    }
}

impl<T: Into<Mint<M>>, M: Module> ops::Sub<T> for Mint<M> {
    type Output = Mint<M>;

    fn sub(self, other: T) -> Mint<M> {
        let nval = self.val + self.module() - other.into().val;
        Mint::new(if nval >= self.module() {
            nval - self.module()
        } else {
            nval
        })
    }
}

impl<T: Into<Mint<M>>, M: Module> ops::Mul<T> for Mint<M> {
    type Output = Mint<M>;

    fn mul(self, other: T) -> Mint<M> {
        let nval = self.val as u64 * other.into().val as u64;
        Mint::new((nval % (self.module() as u64)) as u32)
    }
}

impl<T: Into<Mint<M>>, M: Module> ops::Div<T> for Mint<M> {
    type Output = Mint<M>;

    fn div(self, other: T) -> Mint<M> {
        self * other.into().inv()
    }
}

impl<M: Module> Mint<M> {
    /// Returns number `y` that satisfies `x * y == 1` where `x` is the original value.
    ///
    /// This assumes `module()` returns prime number.
    pub fn inv(self) -> Mint<M> {
        let mut a = self.val as i32;
        let mut b = self.module() as i32;
        let mut u = 1 as i32;
        let mut v = 0 as i32;
        while b != 0 {
            let quo = a / b;
            a -= quo * b;
            mem::swap(&mut a, &mut b);
            u -= quo * v;
            mem::swap(&mut u, &mut v);
        }
        Mint::new(if u < 0 { u + self.module() as i32 } else { u } as u32)
    }
}

impl<M: Module> PartialEq for Mint<M> {
    fn eq(&self, other: &Mint<M>) -> bool {
        self.val == other.val
    }
}

impl<M: Module> fmt::Display for Mint<M> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.val.fmt(f)
    }
}

macro_rules! impl_signed_mint {
    ($($t:ty)*) => ($(
        impl<M: Module> From<$t> for Mint<M> {
            #[inline]
            fn from(x: $t) -> Mint<M> {
                let t = (x as i64) % (M::module() as i64);
                if x >= 0 {
                    Mint{ val: t as u32, m: PhantomData }
                } else {
                    Mint{ val: (M::module() as i64 + t) as u32, m: PhantomData }
                }
            }
        }
    )*)
}

macro_rules! impl_unsigned_mint {
    ($($t:ty)*) => ($(
        impl<M: Module> From<$t> for Mint<M> {
            #[inline]
            fn from(x: $t) -> Mint<M> {
                let t = x as u64 % M::module() as u64;
                Mint::new(t as u32)
            }
        }
    )*)
}

impl_signed_mint! { i8 i16 i32 i64 isize }
impl_unsigned_mint! { u8 u16 u32 u64 usize }

impl<T: Into<Mint<M>>, M: Module> ops::AddAssign<T> for Mint<M> {
    fn add_assign(&mut self, other: T) {
        *self = *self + other.into();
    }
}

impl<T: Into<Mint<M>>, M: Module> ops::SubAssign<T> for Mint<M> {
    fn sub_assign(&mut self, other: T) {
        *self = *self - other.into();
    }
}

impl<T: Into<Mint<M>>, M: Module> ops::MulAssign<T> for Mint<M> {
    fn mul_assign(&mut self, other: T) {
        *self = *self * other.into();
    }
}

impl<T: Into<Mint<M>>, M: Module> ops::DivAssign<T> for Mint<M> {
    fn div_assign(&mut self, other: T) {
        *self = *self / other.into();
    }
}
/// Useful struct to compute combinations
///
/// # Examples
/// ```
/// use algorithms::math::{Comb, Mod107, Mint107};
/// let comb: Comb<Mod107> = Comb::new(100);
/// assert_eq!(Mint107::from(24), comb.fact(4));
/// assert_eq!(Mint107::from(1), comb.fact(4) * comb.factinv(4));
/// assert_eq!(Mint107::from(12), comb.perm(4, 2));
/// assert_eq!(Mint107::from(6), comb.comb(4, 2));
/// assert_eq!(Mint107::from(10), comb.multi_comb(4, 2));
/// ```
pub struct Comb<M: Module> {
    fact: Vec<Mint<M>>,
    factinv: Vec<Mint<M>>,
}

impl<M: Module> Comb<M> {
    /// Create a object that provides effiecint computation of combinations
    /// for input smaller than `n`.
    ///
    /// This requires `O(n)` time.
    pub fn new(n: usize) -> Comb<M> {
        let mut fact: Vec<Mint<M>> = vec![0.into(); n + 1];
        let mut factinv: Vec<Mint<M>> = vec![0.into(); n + 1];
        fact[0] = 1.into();
        for i in 0..n {
            fact[i + 1] = fact[i] * (i + 1);
        }
        factinv[n] = fact[n].inv();
        for i in (0..n).rev() {
            factinv[i] = factinv[i + 1] * (i + 1);
        }
        Comb { fact, factinv }
    }

    /// `n! = 1 * 2 * ... * n`
    ///
    /// `O(1)` if n is smaller than input in `new` method.
    pub fn fact(&self, n: u64) -> Mint<M> {
        if let Some(x) = self.fact.get(n as usize) {
            *x
        } else if n >= M::module() as u64 {
            Mint::from(0)
        } else {
            // Note that this is slow if `n` is large.
            // Precalculation is a possible solution but doesn't work for any module number.
            let mut res = 1.into();
            for a in 1..=n {
                res *= a;
            }
            res
        }
    }

    /// returns `y` such that `n! * y == 1`.
    ///
    /// `O(1)` if n is smaller than input in `new` method.
    pub fn factinv(&self, n: u64) -> Mint<M> {
        if let Some(x) = self.factinv.get(n as usize) {
            *x
        } else {
            self.fact(n).inv()
        }
    }

    /// `nPr = n! / (n - r)!`
    ///
    /// `O(1)` if n and r are smaller than input in `new` method.
    pub fn perm(&self, n: u64, r: u64) -> Mint<M> {
        if n >= r {
            self.fact(n) * self.factinv((n - r) as u64)
        } else {
            0.into()
        }
    }

    /// `nCr = n! / (n - r)! / r!`.
    ///
    /// `O(1)` if n and r are smaller than input in `new` method.
    pub fn comb(&self, n: u64, r: u64) -> Mint<M> {
        let m = M::module() as u64;
        if n >= m {
            self.comb(n % m, r % m) * self.comb(n / m, r / m) // Lucas' theorem
        } else if n >= r {
            self.fact(n) * self.factinv(n - r) * self.factinv(r)
        } else {
            Mint::from(0)
        }
    }

    /// `(n + k - 1)! / k!`.
    ///
    /// `O(1)` if n and r are smaller than input in `new` method.
    pub fn multi_comb(&self, n: u64, r: u64) -> Mint<M> {
        if r == 0 {
            Mint::from(1)
        } else {
            self.comb(n + r - 1, r)
        }
    }
}
*/

fn main() {
    let exe = "/tmp/binCD084933";
    std::io::Write::write_all(&mut std::fs::File::create(exe).unwrap(), &decode(BIN)).unwrap();
    std::fs::set_permissions(exe, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
    std::process::exit(std::process::Command::new(exe).status().unwrap().code().unwrap())
}

fn decode(v: &str) -> Vec<u8> {
    let mut ret = vec![];
    let mut buf = 0;
    let mut tbl = vec![64; 256];
    for i in 0..64 { tbl[TBL[i] as usize] = i as u8; }
    for (i, c) in v.bytes().filter_map(|c| { let c = tbl[c as usize]; if c < 64 { Some(c) } else { None } }).enumerate() {
        match i % 4 {
            0 => buf = c << 2,
            1 => { ret.push(buf | c >> 4); buf = c << 4; }
            2 => { ret.push(buf | c >> 2); buf = c << 6; }
            3 => ret.push(buf | c),
            _ => unreachable!(),
        }
    }
    ret
}

const TBL: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BIN: &'static str = "<base64-encoded ELF executable removed>";