#![allow(unused_imports)]
use pio2::*;
use std::{
    collections::*,
    io::{self, prelude::*},
};
fn run<I: Input, O: Write>(mut pin: I, mut out: O) {
    let t: u32 = 1;
    for _ in 0..t {
        case(&mut pin, &mut out);
    }
}
use mod_int::*;
type Mint = ModInt<VarMod>;
fn case<I: Input, O: Write>(mut pin: I, mut out: O) {
    let (n, m): (usize, u32) = pin.parse();
    set_var_mod(m);
    let mut dp = vec![Mint::new(0); n + 1];
    dp[n] = Mint::new(1);
    let mut sum = Mint::new(0);
    for i in (1..=n).rev() {
        dp[i] += sum;
        sum += dp[i];
        let mut r = 0;
        for d in 2..=i {
            let q = i / d;
            d!(i, q);
            if q == i / (d + 1) {
                r = q;
                break;
            }
            dp[q] = dp[q] + dp[i];
        }
        let mut s = i;
        for j in 1..=r {
            let t = i / (j + 1);
            let a = s - t;
            s = t;
            d!(i, j, a);
            dp[j] = dp[j] + Mint::new(a as u32) * dp[i];
        }
        d!(i, sum);
    }
    let ans = dp[1];
    wln!(out, "{}", ans);
}
fn main() {
    let stdin = io::stdin();
    let mut pin = Scanner::new(stdin.lock());
    let stdout = io::stdout();
    let mut out = stdout.lock();
    run(&mut pin, &mut out);
}
pub mod mod_int {
    use std::{cmp, fmt, marker::PhantomData, ops, sync::atomic};
    #[macro_export]
    macro_rules! def_mint {
        ($modulo:expr, $ModuloTy:ident) => {
            pub struct $ModuloTy;
            impl crate::mod_int::Modulo for $ModuloTy {
                fn modulo() -> u32 {
                    $modulo
                }
            }
            pub type Mint = crate::mod_int::ModInt<$ModuloTy>;
            pub fn mint(x: u32) -> Mint {
                crate::mod_int::ModInt::new(x)
            }
        };
    }
    pub trait Modulo {
        fn modulo() -> u32;
    }
    pub struct VarMod;
    static VAR_MOD: atomic::AtomicU32 = atomic::AtomicU32::new(0);
    pub fn set_var_mod(m: u32) {
        VAR_MOD.store(m, atomic::Ordering::Relaxed);
    }
    impl Modulo for VarMod {
        fn modulo() -> u32 {
            VAR_MOD.load(atomic::Ordering::Relaxed)
        }
    }
    #[repr(transparent)]
    pub struct ModInt<M>(u32, PhantomData<*const M>);
    impl<M: Modulo> ModInt<M> {
        pub fn new(x: u32) -> Self {
            debug_assert!(x < M::modulo());
            Self(x, PhantomData)
        }
        pub fn normalize(self) -> Self {
            if self.0 < M::modulo() {
                self
            } else {
                Self::new(self.0 % M::modulo())
            }
        }
        pub fn get(self) -> u32 {
            self.0
        }
        pub fn inv(self) -> Self {
            assert_ne!(self, Self::new(0));
            self.pow(M::modulo() - 2)
        }
        pub fn half(self) -> Self {
            Self::new(self.0 / 2 + self.0 % 2 * ((M::modulo() + 1) / 2))
        }
        pub fn modulo() -> u32 {
            M::modulo()
        }
    }
    impl<M: Modulo> ops::Neg for ModInt<M> {
        type Output = Self;
        fn neg(self) -> Self {
            Self::new(if self.0 == 0 { 0 } else { M::modulo() - self.0 })
        }
    }
    impl<M: Modulo> ops::Neg for &ModInt<M> {
        type Output = ModInt<M>;
        fn neg(self) -> Self::Output {
            -(*self)
        }
    }
    impl<M: Modulo> ops::Add for ModInt<M> {
        type Output = Self;
        fn add(self, rhs: Self) -> Self {
            let s = self.0 + rhs.0;
            Self::new(if s < M::modulo() { s } else { s - M::modulo() })
        }
    }
    impl<M: Modulo> ops::Sub for ModInt<M> {
        type Output = Self;
        fn sub(self, rhs: Self) -> Self {
            Self::new(if self.0 >= rhs.0 {
                self.0 - rhs.0
            } else {
                M::modulo() + self.0 - rhs.0
            })
        }
    }
    impl<M: Modulo> ops::Mul for ModInt<M> {
        type Output = Self;
        fn mul(self, rhs: Self) -> Self {
            Self::new((self.0 as u64 * rhs.0 as u64 % M::modulo() as u64) as u32)
        }
    }
    impl<M: Modulo> ops::Div for ModInt<M> {
        type Output = Self;
        fn div(self, rhs: Self) -> Self {
            self * rhs.inv()
        }
    }
    macro_rules ! op_impl { ($ ($ Op : ident $ op : ident $ OpAssign : ident $ op_assign : ident) *) => { $ (impl < M : Modulo > ops ::$ Op <& Self > for ModInt < M > { type Output = Self ; fn $ op (self , rhs : & Self) -> Self { self .$ op (* rhs) } } impl < M : Modulo > ops ::$ Op < ModInt < M >> for & ModInt < M > { type Output = ModInt < M >; fn $ op (self , rhs : ModInt < M >) -> ModInt < M > { (* self) .$ op (rhs) } } impl < M : Modulo > ops ::$ Op <& ModInt < M >> for & ModInt < M > { type Output = ModInt < M >; fn $ op (self , rhs : & ModInt < M >) -> ModInt < M > { (* self) .$ op (* rhs) } } impl < M : Modulo > ops ::$ OpAssign for ModInt < M > { fn $ op_assign (& mut self , rhs : Self) { * self = ops ::$ Op ::$ op (* self , rhs) ; } } impl < M : Modulo > ops ::$ OpAssign <& ModInt < M >> for ModInt < M > { fn $ op_assign (& mut self , rhs : & ModInt < M >) { self .$ op_assign (* rhs) ; } }) * } ; }
    op_impl! { Add add AddAssign add_assign Sub sub SubAssign sub_assign Mul mul MulAssign mul_assign Div div DivAssign div_assign }
    impl<M: Modulo> std::iter::Sum for ModInt<M> {
        fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
            iter.fold(ModInt::new(0), |x, y| x + y)
        }
    }
    impl<'a, M: Modulo + 'a> std::iter::Sum<&'a ModInt<M>> for ModInt<M> {
        fn sum<I: Iterator<Item = &'a ModInt<M>>>(iter: I) -> Self {
            iter.copied().sum()
        }
    }
    impl<M: Modulo> std::iter::Product for ModInt<M> {
        fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
            iter.fold(ModInt::new(1), |x, y| x * y)
        }
    }
    impl<'a, M: Modulo + 'a> std::iter::Product<&'a ModInt<M>> for ModInt<M> {
        fn product<I: Iterator<Item = &'a ModInt<M>>>(iter: I) -> Self {
            iter.copied().product()
        }
    }
    pub trait Pow<T> {
        fn pow(self, n: T) -> Self;
    }
    macro_rules ! mod_int_pow_impl { ($ ($ uty : ident $ ity : ident) *) => { $ (impl < M : Modulo > Pow <$ uty > for ModInt < M > { fn pow (mut self , mut n : $ uty) -> Self { let mut y = Self :: new (1) ; while n > 0 { if n & 1 == 1 { y *= self ; } self *= self ; n /= 2 ; } y } } impl < M : Modulo > Pow <$ ity > for ModInt < M > { fn pow (self , n : $ ity) -> Self { if n >= 0 { self . pow (n as $ uty) } else { self . inv () . pow (- n as $ uty) } } }) * } ; }
    mod_int_pow_impl ! (usize isize u32 i32 u64 i64);
    macro_rules ! mod_int_from_impl { ($ ($ T : ident) *) => { $ (impl < M : Modulo > From <$ T > for ModInt < M > { # [allow (unused_comparisons)] fn from (x : $ T) -> Self { if M :: modulo () <= $ T :: max_value () as u32 { Self :: new (x . rem_euclid (M :: modulo () as $ T) as u32) } else if x < 0 { Self :: new ((M :: modulo () as i32 + x as i32) as u32) } else { Self :: new (x as u32) } } }) * } }
    mod_int_from_impl ! (isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128);
    impl<M: Modulo> From<bool> for ModInt<M> {
        fn from(x: bool) -> Self {
            Self::new(x as u32)
        }
    }
    impl<M> Copy for ModInt<M> {}
    impl<M> Clone for ModInt<M> {
        fn clone(&self) -> Self {
            *self
        }
    }
    impl<M: Modulo> Default for ModInt<M> {
        fn default() -> Self {
            Self::new(0)
        }
    }
    impl<M> cmp::PartialEq for ModInt<M> {
        fn eq(&self, other: &Self) -> bool {
            self.0 == other.0
        }
    }
    impl<M> cmp::Eq for ModInt<M> {}
    impl<M> cmp::PartialOrd for ModInt<M> {
        fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
            self.0.partial_cmp(&other.0)
        }
    }
    impl<M> cmp::Ord for ModInt<M> {
        fn cmp(&self, other: &Self) -> cmp::Ordering {
            self.0.cmp(&other.0)
        }
    }
    impl<M> std::hash::Hash for ModInt<M> {
        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
            self.0.hash(state);
        }
    }
    impl<M> fmt::Display for ModInt<M> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fmt(f)
        }
    }
    impl<M> fmt::Debug for ModInt<M> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fmt(f)
        }
    }
}
pub mod macros {
    #[macro_export]
    macro_rules ! w { ($ ($ arg : tt) *) => { write ! ($ ($ arg) *) . unwrap () ; } }
    #[macro_export]
    macro_rules ! wln { ($ dst : expr $ (, $ ($ arg : tt) *) ?) => { { writeln ! ($ dst $ (, $ ($ arg) *) ?) . unwrap () ; # [cfg (debug_assertions)] $ dst . flush () . unwrap () ; } } }
    #[macro_export]
    macro_rules! w_iter {
        ($dst:expr, $fmt:expr, $iter:expr, $delim:expr) => {{
            let mut first = true;
            for elem in $iter {
                if first {
                    w!($dst, $fmt, elem);
                    first = false;
                } else {
                    w!($dst, concat!($delim, $fmt), elem);
                }
            }
        }};
        ($dst:expr, $fmt:expr, $iter:expr) => {
            w_iter!($dst, $fmt, $iter, " ")
        };
    }
    #[macro_export]
    macro_rules ! w_iter_ln { ($ dst : expr , $ ($ t : tt) *) => { { w_iter ! ($ dst , $ ($ t) *) ; wln ! ($ dst) ; } } }
    #[macro_export]
    macro_rules ! e { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprint ! ($ ($ t) *) } }
    #[macro_export]
    macro_rules ! eln { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprintln ! ($ ($ t) *) } }
    #[macro_export]
    macro_rules ! __tstr { ($ h : expr $ (, $ t : expr) +) => { concat ! (__tstr ! ($ ($ t) ,+) , ", " , __tstr ! (@)) } ; ($ h : expr) => { concat ! (__tstr ! () , " " , __tstr ! (@)) } ; () => { "\x1B[94m[{}:{}]\x1B[0m" } ; (@) => { "\x1B[1;92m{}\x1B[0m = {:?}" } }
    #[macro_export]
    macro_rules ! d { ($ ($ a : expr) ,*) => { eln ! (__tstr ! ($ ($ a) ,*) , file ! () , line ! () , $ (stringify ! ($ a) , $ a) ,*) } ; }
}
pub mod pio2 {
    use std::{
        io::prelude::*,
        marker::PhantomData,
        mem::{self, MaybeUninit},
        str,
    };
    pub trait Input {
        fn bytes(&mut self) -> &[u8];
        #[inline]
        fn str(&mut self) -> &str {
            str::from_utf8(self.bytes()).unwrap()
        }
        #[inline]
        fn parse<T>(&mut self) -> T
        where
            DefaultParser: Parser<T>,
        {
            self.parse_with(DefaultParser)
        }
        #[inline]
        fn parse_with<T, P: Parser<T>>(&mut self, mut parser: P) -> T {
            parser.parse(self)
        }
        #[inline]
        fn seq<T>(&mut self, n: usize) -> Seq<Self, T, DefaultParser>
        where
            DefaultParser: Parser<T>,
        {
            self.seq_with(n, DefaultParser)
        }
        #[inline]
        fn seq_with<T, P: Parser<T>>(&mut self, n: usize, parser: P) -> Seq<Self, T, P> {
            Seq {
                src: self,
                rest: n,
                parser,
                phantom: PhantomData,
            }
        }
    }
    impl<I: Input> Input for &mut I {
        #[inline]
        fn bytes(&mut self) -> &[u8] {
            (**self).bytes()
        }
    }
    pub struct Scanner<R> {
        src: R,
        buf: Vec<u8>,
        pos: usize,
        len: usize,
    }
    impl<R: Read> Scanner<R> {
        #[inline]
        pub fn new(src: R) -> Self {
            Self {
                src,
                buf: vec![0; 1 << 16],
                pos: 0,
                len: 0,
            }
        }
        fn read(&mut self) -> usize {
            if self.pos > 0 {
                self.buf.copy_within(self.pos..self.len, 0);
                self.len -= self.pos;
                self.pos = 0;
            } else if self.len >= self.buf.len() {
                self.buf.resize(2 * self.buf.len(), 0);
            }
            let n = self.src.read(&mut self.buf[self.len..]).unwrap();
            self.len += n;
            assert!(self.len <= self.buf.len());
            n
        }
    }
    impl<R: Read> Input for Scanner<R> {
        fn bytes(&mut self) -> &[u8] {
            loop {
                while let Some(d) = unsafe { self.buf.get_unchecked(self.pos..self.len) }
                    .iter()
                    .position(u8::is_ascii_whitespace)
                {
                    let p = self.pos;
                    self.pos += d + 1;
                    if d > 0 {
                        return unsafe { self.buf.get_unchecked(p..p + d) };
                    }
                }
                if self.read() == 0 {
                    let p = self.pos;
                    if p == self.len {
                        panic!("reached EOF");
                    }
                    self.pos = self.len;
                    return unsafe { self.buf.get_unchecked(p..self.len) };
                }
            }
        }
    }
    pub struct Seq<'a, I: ?Sized, T, P> {
        src: &'a mut I,
        rest: usize,
        parser: P,
        phantom: PhantomData<*const T>,
    }
    impl<'a, I: Input + ?Sized, T, P: Parser<T>> Iterator for Seq<'a, I, T, P> {
        type Item = T;
        #[inline]
        fn next(&mut self) -> Option<T> {
            if self.rest > 0 {
                self.rest -= 1;
                Some(self.src.parse_with(&mut self.parser))
            } else {
                None
            }
        }
        #[inline]
        fn size_hint(&self) -> (usize, Option<usize>) {
            (self.rest, Some(self.rest))
        }
    }
    impl<'a, I: Input + ?Sized, T, P: Parser<T>> ExactSizeIterator for Seq<'a, I, T, P> {}
    pub trait Parser<T> {
        fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> T;
    }
    impl<T, P: Parser<T>> Parser<T> for &mut P {
        #[inline]
        fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> T {
            (*self).parse(src)
        }
    }
    #[derive(Clone, Copy, Debug)]
    pub struct DefaultParser;
    macro_rules ! impls { ($ m : ident , $ ($ ty : ty) ,*) => { $ ($ m ! ($ ty) ;) * } ; }
    macro_rules! int {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    let f = |s: &[u8]| s.iter().fold(0, |x, b| 10 * x + (b & 0xf) as $ty);
                    let s = src.bytes();
                    if let Some((&b'-', t)) = s.split_first() {
                        -f(t)
                    } else {
                        f(s)
                    }
                }
            }
        };
    }
    impls!(int, isize, i8, i16, i32, i64, i128);
    macro_rules! uint {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    src.bytes().iter().fold(0, |x, b| 10 * x + (b & 0xf) as $ty)
                }
            }
        };
    }
    impls!(uint, usize, u8, u16, u32, u64, u128);
    macro_rules! from_bytes {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    src.bytes().into()
                }
            }
        };
    }
    impls!(from_bytes, Vec<u8>, Box<[u8]>);
    macro_rules! from_str {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    src.str().parse::<$ty>().expect("failed to parse")
                }
            }
        };
    }
    impls!(from_str, String, char, f32, f64);
    macro_rules ! tuple { ($ ($ T : ident) ,+) => { impl <$ ($ T) ,+> Parser < ($ ($ T ,) +) > for DefaultParser where $ (DefaultParser : Parser <$ T >) ,+ { # [inline] fn parse < I : Input + ? Sized > (& mut self , src : & mut I) -> ($ ($ T ,) +) { ($ (< Self as Parser <$ T >>:: parse (self , src) ,) +) } } } ; }
    tuple!(A);
    tuple!(A, B);
    tuple!(A, B, C);
    tuple!(A, B, C, D);
    tuple!(A, B, C, D, E);
    tuple!(A, B, C, D, E, F);
    tuple!(A, B, C, D, E, F, G);
    tuple!(A, B, C, D, E, F, G, H);
    macro_rules ! array { ($ ($ N : literal) *) => { $ (impl < T > Parser < [T ; $ N] > for DefaultParser where DefaultParser : Parser < T > { fn parse < I : Input + ? Sized > (& mut self , src : & mut I) -> [T ; $ N] { unsafe { let mut arr : [MaybeUninit < T >; $ N] = MaybeUninit :: uninit () . assume_init () ; for elem in & mut arr { * elem = MaybeUninit :: new (src . parse ()) ; } mem :: transmute_copy (& arr) } } }) * } }
    array ! (1 2 3 4 5 6 7 8);
}


#![allow(unused_imports)]
use pio2::*;
use procon_temp::mod_int::ModInt;
use std::{
    collections::*,
    io::{self, prelude::*},
};
fn run<I: Input, O: Write>(mut pin: I, mut out: O) {
    let t: u32 = 1;
    for _ in 0..t {
        case(&mut pin, &mut out);
    }
}
fn case<I: Input, O: Write>(mut pin: I, mut out: O) {
    use mod_int::*;
    type Mint = ModInt<VarMod>;
    let (n, m): (usize, u32) = pin.parse();
    set_var_mod(m);
    let mut div = vec![Mint::new(0); n + 1];
    let mut dp = vec![Mint::new(0); n + 1];
    dp[1] = Mint::new(1);
    let mut sum = Mint::new(0);
    for i in 1..=n {
        div[i] = div[i] + div[i - 1];
        dp[i] = dp[i] + sum + div[i];
        sum += dp[i];
        for z in 2.. {
            if i * z > n {
                break;
            }
            div[i * z] += dp[i];
            if let Some(d) = div.get_mut((i + 1) * z) {
                *d -= dp[i];
            }
        }
    }
    let ans = dp[n];
    wln!(out, "{}", ans);
}
fn main() {
    let stdin = io::stdin();
    let mut pin = Scanner::new(stdin.lock());
    let stdout = io::stdout();
    let mut out = stdout.lock();
    run(&mut pin, &mut out);
}
pub mod mod_int {
    use std::{cmp, fmt, marker::PhantomData, ops, sync::atomic};
    #[macro_export]
    macro_rules! def_mint {
        ($modulo:expr, $ModuloTy:ident) => {
            pub struct $ModuloTy;
            impl crate::mod_int::Modulo for $ModuloTy {
                fn modulo() -> u32 {
                    $modulo
                }
            }
            pub type Mint = crate::mod_int::ModInt<$ModuloTy>;
            pub fn mint(x: u32) -> Mint {
                crate::mod_int::ModInt::new(x)
            }
        };
    }
    pub trait Modulo {
        fn modulo() -> u32;
    }
    pub struct VarMod;
    static VAR_MOD: atomic::AtomicU32 = atomic::AtomicU32::new(0);
    pub fn set_var_mod(m: u32) {
        VAR_MOD.store(m, atomic::Ordering::Relaxed);
    }
    impl Modulo for VarMod {
        fn modulo() -> u32 {
            VAR_MOD.load(atomic::Ordering::Relaxed)
        }
    }
    #[repr(transparent)]
    pub struct ModInt<M>(u32, PhantomData<*const M>);
    impl<M: Modulo> ModInt<M> {
        pub fn new(x: u32) -> Self {
            debug_assert!(x < M::modulo());
            Self(x, PhantomData)
        }
        pub fn normalize(self) -> Self {
            if self.0 < M::modulo() {
                self
            } else {
                Self::new(self.0 % M::modulo())
            }
        }
        pub fn get(self) -> u32 {
            self.0
        }
        pub fn inv(self) -> Self {
            assert_ne!(self, Self::new(0));
            self.pow(M::modulo() - 2)
        }
        pub fn half(self) -> Self {
            Self::new(self.0 / 2 + self.0 % 2 * ((M::modulo() + 1) / 2))
        }
        pub fn modulo() -> u32 {
            M::modulo()
        }
    }
    impl<M: Modulo> ops::Neg for ModInt<M> {
        type Output = Self;
        fn neg(self) -> Self {
            Self::new(if self.0 == 0 { 0 } else { M::modulo() - self.0 })
        }
    }
    impl<M: Modulo> ops::Neg for &ModInt<M> {
        type Output = ModInt<M>;
        fn neg(self) -> Self::Output {
            -(*self)
        }
    }
    impl<M: Modulo> ops::Add for ModInt<M> {
        type Output = Self;
        fn add(self, rhs: Self) -> Self {
            let s = self.0 + rhs.0;
            Self::new(if s < M::modulo() { s } else { s - M::modulo() })
        }
    }
    impl<M: Modulo> ops::Sub for ModInt<M> {
        type Output = Self;
        fn sub(self, rhs: Self) -> Self {
            Self::new(if self.0 >= rhs.0 {
                self.0 - rhs.0
            } else {
                M::modulo() + self.0 - rhs.0
            })
        }
    }
    impl<M: Modulo> ops::Mul for ModInt<M> {
        type Output = Self;
        fn mul(self, rhs: Self) -> Self {
            Self::new((self.0 as u64 * rhs.0 as u64 % M::modulo() as u64) as u32)
        }
    }
    impl<M: Modulo> ops::Div for ModInt<M> {
        type Output = Self;
        fn div(self, rhs: Self) -> Self {
            self * rhs.inv()
        }
    }
    macro_rules ! op_impl { ($ ($ Op : ident $ op : ident $ OpAssign : ident $ op_assign : ident) *) => { $ (impl < M : Modulo > ops ::$ Op <& Self > for ModInt < M > { type Output = Self ; fn $ op (self , rhs : & Self) -> Self { self .$ op (* rhs) } } impl < M : Modulo > ops ::$ Op < ModInt < M >> for & ModInt < M > { type Output = ModInt < M >; fn $ op (self , rhs : ModInt < M >) -> ModInt < M > { (* self) .$ op (rhs) } } impl < M : Modulo > ops ::$ Op <& ModInt < M >> for & ModInt < M > { type Output = ModInt < M >; fn $ op (self , rhs : & ModInt < M >) -> ModInt < M > { (* self) .$ op (* rhs) } } impl < M : Modulo > ops ::$ OpAssign for ModInt < M > { fn $ op_assign (& mut self , rhs : Self) { * self = ops ::$ Op ::$ op (* self , rhs) ; } } impl < M : Modulo > ops ::$ OpAssign <& ModInt < M >> for ModInt < M > { fn $ op_assign (& mut self , rhs : & ModInt < M >) { self .$ op_assign (* rhs) ; } }) * } ; }
    op_impl! { Add add AddAssign add_assign Sub sub SubAssign sub_assign Mul mul MulAssign mul_assign Div div DivAssign div_assign }
    impl<M: Modulo> std::iter::Sum for ModInt<M> {
        fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
            iter.fold(ModInt::new(0), |x, y| x + y)
        }
    }
    impl<'a, M: Modulo + 'a> std::iter::Sum<&'a ModInt<M>> for ModInt<M> {
        fn sum<I: Iterator<Item = &'a ModInt<M>>>(iter: I) -> Self {
            iter.copied().sum()
        }
    }
    impl<M: Modulo> std::iter::Product for ModInt<M> {
        fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
            iter.fold(ModInt::new(1), |x, y| x * y)
        }
    }
    impl<'a, M: Modulo + 'a> std::iter::Product<&'a ModInt<M>> for ModInt<M> {
        fn product<I: Iterator<Item = &'a ModInt<M>>>(iter: I) -> Self {
            iter.copied().product()
        }
    }
    pub trait Pow<T> {
        fn pow(self, n: T) -> Self;
    }
    macro_rules ! mod_int_pow_impl { ($ ($ uty : ident $ ity : ident) *) => { $ (impl < M : Modulo > Pow <$ uty > for ModInt < M > { fn pow (mut self , mut n : $ uty) -> Self { let mut y = Self :: new (1) ; while n > 0 { if n & 1 == 1 { y *= self ; } self *= self ; n /= 2 ; } y } } impl < M : Modulo > Pow <$ ity > for ModInt < M > { fn pow (self , n : $ ity) -> Self { if n >= 0 { self . pow (n as $ uty) } else { self . inv () . pow (- n as $ uty) } } }) * } ; }
    mod_int_pow_impl ! (usize isize u32 i32 u64 i64);
    macro_rules ! mod_int_from_impl { ($ ($ T : ident) *) => { $ (impl < M : Modulo > From <$ T > for ModInt < M > { # [allow (unused_comparisons)] fn from (x : $ T) -> Self { if M :: modulo () <= $ T :: max_value () as u32 { Self :: new (x . rem_euclid (M :: modulo () as $ T) as u32) } else if x < 0 { Self :: new ((M :: modulo () as i32 + x as i32) as u32) } else { Self :: new (x as u32) } } }) * } }
    mod_int_from_impl ! (isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128);
    impl<M: Modulo> From<bool> for ModInt<M> {
        fn from(x: bool) -> Self {
            Self::new(x as u32)
        }
    }
    impl<M> Copy for ModInt<M> {}
    impl<M> Clone for ModInt<M> {
        fn clone(&self) -> Self {
            *self
        }
    }
    impl<M: Modulo> Default for ModInt<M> {
        fn default() -> Self {
            Self::new(0)
        }
    }
    impl<M> cmp::PartialEq for ModInt<M> {
        fn eq(&self, other: &Self) -> bool {
            self.0 == other.0
        }
    }
    impl<M> cmp::Eq for ModInt<M> {}
    impl<M> cmp::PartialOrd for ModInt<M> {
        fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
            self.0.partial_cmp(&other.0)
        }
    }
    impl<M> cmp::Ord for ModInt<M> {
        fn cmp(&self, other: &Self) -> cmp::Ordering {
            self.0.cmp(&other.0)
        }
    }
    impl<M> std::hash::Hash for ModInt<M> {
        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
            self.0.hash(state);
        }
    }
    impl<M> fmt::Display for ModInt<M> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fmt(f)
        }
    }
    impl<M> fmt::Debug for ModInt<M> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fmt(f)
        }
    }
}
pub mod macros {
    #[macro_export]
    macro_rules ! w { ($ ($ arg : tt) *) => { write ! ($ ($ arg) *) . unwrap () ; } }
    #[macro_export]
    macro_rules ! wln { ($ dst : expr $ (, $ ($ arg : tt) *) ?) => { { writeln ! ($ dst $ (, $ ($ arg) *) ?) . unwrap () ; # [cfg (debug_assertions)] $ dst . flush () . unwrap () ; } } }
    #[macro_export]
    macro_rules! w_iter {
        ($dst:expr, $fmt:expr, $iter:expr, $delim:expr) => {{
            let mut first = true;
            for elem in $iter {
                if first {
                    w!($dst, $fmt, elem);
                    first = false;
                } else {
                    w!($dst, concat!($delim, $fmt), elem);
                }
            }
        }};
        ($dst:expr, $fmt:expr, $iter:expr) => {
            w_iter!($dst, $fmt, $iter, " ")
        };
    }
    #[macro_export]
    macro_rules ! w_iter_ln { ($ dst : expr , $ ($ t : tt) *) => { { w_iter ! ($ dst , $ ($ t) *) ; wln ! ($ dst) ; } } }
    #[macro_export]
    macro_rules ! e { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprint ! ($ ($ t) *) } }
    #[macro_export]
    macro_rules ! eln { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprintln ! ($ ($ t) *) } }
    #[macro_export]
    macro_rules ! __tstr { ($ h : expr $ (, $ t : expr) +) => { concat ! (__tstr ! ($ ($ t) ,+) , ", " , __tstr ! (@)) } ; ($ h : expr) => { concat ! (__tstr ! () , " " , __tstr ! (@)) } ; () => { "\x1B[94m[{}:{}]\x1B[0m" } ; (@) => { "\x1B[1;92m{}\x1B[0m = {:?}" } }
    #[macro_export]
    macro_rules ! d { ($ ($ a : expr) ,*) => { eln ! (__tstr ! ($ ($ a) ,*) , file ! () , line ! () , $ (stringify ! ($ a) , $ a) ,*) } ; }
}
pub mod pio2 {
    use std::{
        io::prelude::*,
        marker::PhantomData,
        mem::{self, MaybeUninit},
        str,
    };
    pub trait Input {
        fn bytes(&mut self) -> &[u8];
        #[inline]
        fn str(&mut self) -> &str {
            str::from_utf8(self.bytes()).unwrap()
        }
        #[inline]
        fn parse<T>(&mut self) -> T
        where
            DefaultParser: Parser<T>,
        {
            self.parse_with(DefaultParser)
        }
        #[inline]
        fn parse_with<T, P: Parser<T>>(&mut self, mut parser: P) -> T {
            parser.parse(self)
        }
        #[inline]
        fn seq<T>(&mut self, n: usize) -> Seq<Self, T, DefaultParser>
        where
            DefaultParser: Parser<T>,
        {
            self.seq_with(n, DefaultParser)
        }
        #[inline]
        fn seq_with<T, P: Parser<T>>(&mut self, n: usize, parser: P) -> Seq<Self, T, P> {
            Seq {
                src: self,
                rest: n,
                parser,
                phantom: PhantomData,
            }
        }
    }
    impl<I: Input> Input for &mut I {
        #[inline]
        fn bytes(&mut self) -> &[u8] {
            (**self).bytes()
        }
    }
    pub struct Scanner<R> {
        src: R,
        buf: Vec<u8>,
        pos: usize,
        len: usize,
    }
    impl<R: Read> Scanner<R> {
        #[inline]
        pub fn new(src: R) -> Self {
            Self {
                src,
                buf: vec![0; 1 << 16],
                pos: 0,
                len: 0,
            }
        }
        fn read(&mut self) -> usize {
            if self.pos > 0 {
                self.buf.copy_within(self.pos..self.len, 0);
                self.len -= self.pos;
                self.pos = 0;
            } else if self.len >= self.buf.len() {
                self.buf.resize(2 * self.buf.len(), 0);
            }
            let n = self.src.read(&mut self.buf[self.len..]).unwrap();
            self.len += n;
            assert!(self.len <= self.buf.len());
            n
        }
    }
    impl<R: Read> Input for Scanner<R> {
        fn bytes(&mut self) -> &[u8] {
            loop {
                while let Some(d) = unsafe { self.buf.get_unchecked(self.pos..self.len) }
                    .iter()
                    .position(u8::is_ascii_whitespace)
                {
                    let p = self.pos;
                    self.pos += d + 1;
                    if d > 0 {
                        return unsafe { self.buf.get_unchecked(p..p + d) };
                    }
                }
                if self.read() == 0 {
                    let p = self.pos;
                    if p == self.len {
                        panic!("reached EOF");
                    }
                    self.pos = self.len;
                    return unsafe { self.buf.get_unchecked(p..self.len) };
                }
            }
        }
    }
    pub struct Seq<'a, I: ?Sized, T, P> {
        src: &'a mut I,
        rest: usize,
        parser: P,
        phantom: PhantomData<*const T>,
    }
    impl<'a, I: Input + ?Sized, T, P: Parser<T>> Iterator for Seq<'a, I, T, P> {
        type Item = T;
        #[inline]
        fn next(&mut self) -> Option<T> {
            if self.rest > 0 {
                self.rest -= 1;
                Some(self.src.parse_with(&mut self.parser))
            } else {
                None
            }
        }
        #[inline]
        fn size_hint(&self) -> (usize, Option<usize>) {
            (self.rest, Some(self.rest))
        }
    }
    impl<'a, I: Input + ?Sized, T, P: Parser<T>> ExactSizeIterator for Seq<'a, I, T, P> {}
    pub trait Parser<T> {
        fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> T;
    }
    impl<T, P: Parser<T>> Parser<T> for &mut P {
        #[inline]
        fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> T {
            (*self).parse(src)
        }
    }
    #[derive(Clone, Copy, Debug)]
    pub struct DefaultParser;
    macro_rules ! impls { ($ m : ident , $ ($ ty : ty) ,*) => { $ ($ m ! ($ ty) ;) * } ; }
    macro_rules! int {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    let f = |s: &[u8]| s.iter().fold(0, |x, b| 10 * x + (b & 0xf) as $ty);
                    let s = src.bytes();
                    if let Some((&b'-', t)) = s.split_first() {
                        -f(t)
                    } else {
                        f(s)
                    }
                }
            }
        };
    }
    impls!(int, isize, i8, i16, i32, i64, i128);
    macro_rules! uint {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    src.bytes().iter().fold(0, |x, b| 10 * x + (b & 0xf) as $ty)
                }
            }
        };
    }
    impls!(uint, usize, u8, u16, u32, u64, u128);
    macro_rules! from_bytes {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    src.bytes().into()
                }
            }
        };
    }
    impls!(from_bytes, Vec<u8>, Box<[u8]>);
    macro_rules! from_str {
        ($ty:ty) => {
            impl Parser<$ty> for DefaultParser {
                #[inline]
                fn parse<I: Input + ?Sized>(&mut self, src: &mut I) -> $ty {
                    src.str().parse::<$ty>().expect("failed to parse")
                }
            }
        };
    }
    impls!(from_str, String, char, f32, f64);
    macro_rules ! tuple { ($ ($ T : ident) ,+) => { impl <$ ($ T) ,+> Parser < ($ ($ T ,) +) > for DefaultParser where $ (DefaultParser : Parser <$ T >) ,+ { # [inline] fn parse < I : Input + ? Sized > (& mut self , src : & mut I) -> ($ ($ T ,) +) { ($ (< Self as Parser <$ T >>:: parse (self , src) ,) +) } } } ; }
    tuple!(A);
    tuple!(A, B);
    tuple!(A, B, C);
    tuple!(A, B, C, D);
    tuple!(A, B, C, D, E);
    tuple!(A, B, C, D, E, F);
    tuple!(A, B, C, D, E, F, G);
    tuple!(A, B, C, D, E, F, G, H);
    macro_rules ! array { ($ ($ N : literal) *) => { $ (impl < T > Parser < [T ; $ N] > for DefaultParser where DefaultParser : Parser < T > { fn parse < I : Input + ? Sized > (& mut self , src : & mut I) -> [T ; $ N] { unsafe { let mut arr : [MaybeUninit < T >; $ N] = MaybeUninit :: uninit () . assume_init () ; for elem in & mut arr { * elem = MaybeUninit :: new (src . parse ()) ; } mem :: transmute_copy (& arr) } } }) * } }
    array ! (1 2 3 4 5 6 7 8);
}


fn main() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let n: usize = sc.read();
    let m: i64 = sc.read();
    let mut dp = vec![0; n + 1];
    let mut suffix_sum = 0;
    dp[n] = 1;

    for cur in (2..=n).rev() {
        dp[cur] = mod_add(dp[cur], suffix_sum, m);
        suffix_sum = mod_add(suffix_sum, dp[cur], m);

        let mut min_next = n;
        for z in 2.. {
            if z * z > cur {
                break;
            }
            let next = cur / z;
            dp[next] = mod_add(dp[next], dp[cur], m);
            min_next = min_next.min(next);
        }

        for next in 1..min_next {
            let z = cur / next;
            let z_next = cur / (next + 1);
            let count = z - z_next;
            let add = ((count as i64) * dp[cur]) % m;
            dp[next] = mod_add(dp[next], add, m);
            if z_next == 1 {
                break;
            }
        }
    }
    dp[1] = mod_add(dp[1], suffix_sum, m);

    // eprintln!("{:?}", dp);
    println!("{}", dp[1]);
}

fn mod_add(x: i64, y: i64, m: i64) -> i64 {
    let r = x + y;
    if r >= m {
        r - m
    } else {
        r
    }
}

fn mod_sub(x: i64, y: i64, m: i64) -> i64 {
    let r = x + m - y;
    if r >= m {
        r - m
    } else {
        r
    }
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: ToString>(&mut self, s: S) {
        use std::io::Write;
        self.1.write_all(s.to_string().as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn usize0(&mut self) -> usize {
        self.read::<usize>() - 1
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}


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

macro_rules! parse_line {
  ($($t: ty),+) => ({
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let mut iter = line.split_whitespace();
    ($(iter.next().unwrap().parse::<$t>().unwrap()),+)
  })
}

#[allow(dead_code)]
fn count_number(n : usize, m : usize) -> usize{
    if n == 2 {
        return 2;
    }
    let mut save = vec![1; n + 1];
    for i in 2..n{
        save[i] = (save[i] + i - i / 2) % m;
        let x = save[i];
        for j in (i + 1) .. (n + 1){
            let start = if (j / (i + 1)) > 1 { j / (i + 1) } else { 1 };
            let way = (j / i) + 1 - start;
            save[j] = (save[j] + way * x) % m;
        }
    }
    return (save[n] + n - (n / 2)) % m;
}

#[allow(dead_code)]
fn count_number2(n : usize, m : i32) -> i32{
    fn div_way(x : usize, k : usize) -> i32{
        let (a, b) = ((x / k) as i32, (x / (k + 1)) as i32);
        if b > 1 { a - b } else { a - 1 }
    }

    fn diff(x : usize, k : usize) -> i32{
        div_way(x, k) - div_way(x - 1, k)
    }

    if n == 2 {
        return 2;
    }
    let mut save = vec![0; n + 1];
    save[1] = 1;
    save[2] = -2;
    for i in 2..n + 1{
        if i % 2 == 0 {
            save[i] = (save[i] + 2 * save[i - 1] + save[ i / 2 ] + diff(i, 1)) % m;
        }
        else {
            save[i] = (save[i] + 2 * save[i - 1] + diff(i, 1)) % m;
        }

        let x = save[i];
        for j in (2 * i + 1) .. (n + 1){
            save[j] = (save[j] + diff(j, i) * x) % m;
        }
    }
    return save[n];
}

#[allow(dead_code)]
pub fn main(){
    let stdout = io::stdout();
    let lock_out = stdout.lock();
    let mut buff = BufWriter::new(lock_out);

    let (n, m) = parse_line!(usize, i32);
    buff.write_fmt(format_args!("{}\n", count_number2(n, m))).unwrap();
}


use std::cmp::max;
use std::io::{self, prelude::*, BufWriter};
use std::str::FromStr;

type M = DynamicModInt;

fn solve<R: BufRead, W: Write>(scan: &mut Scanner<R>, out: &mut W) {
    let n: usize = scan.next();
    M::set_modulus(scan.next());

    let mut dp = vec![M::zero(); n + 1];
    dp[1] = M::one();
    let mut sum = M::one();
    for i in 2..=n {
        let root = (i as f64).sqrt() as usize;
        for j in 2..=root {
            let delta = dp[i / j];
            dp[i] += delta;
        }
        // i = 2 root = 1
        // high = 2
        // low = 2
        for k in 1..=root {
            let high = i / k;
            let low = max(2, max(root + 1, i / (k + 1) + 1));
            if low <= high {
                assert_eq!(i / low, k);
                assert_eq!(i / high, k);
                let delta = dp[k] * M::from(high - low + 1);
                dp[i] += delta;
            }
        }

        dp[i] += sum;
        sum += dp[i];
    }
    writeln!(out, "{}", dp[n]).ok();
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = BufWriter::new(stdout.lock());

    let tests = 1; // scan.next::<usize>();
    for _ in 0..tests {
        solve(&mut scan, &mut out);
    }
}

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

impl<R: BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: vec![],
        }
    }

    pub fn next<T: FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().unwrap();
            }
            let mut line = String::new();
            self.reader.read_line(&mut line).unwrap();
            self.buffer = line
                .split_ascii_whitespace()
                .rev()
                .map(String::from)
                .collect();
        }
    }

    pub fn next_vec<T: FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next()).collect()
    }
}
// }}}
// {{{ DynamicModInt
use std::fmt;
use std::iter::{Product, Sum};
use std::ops::*;

#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
pub struct DynamicModInt(pub i32);

impl Default for DynamicModInt {
    fn default() -> Self {
        DynamicModInt(0)
    }
}

impl fmt::Display for DynamicModInt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl DynamicModInt {
    pub fn set_modulus(modulus: i32) {
        *Self::modulus_ref() = modulus;
    }

    pub fn modulus() -> i32 {
        *Self::modulus_ref()
    }

    fn modulus_ref() -> &'static mut i32 {
        static mut MODULES: i32 = 0;
        return unsafe { &mut MODULES };
    }

    pub fn raw(val: i32) -> Self {
        DynamicModInt(val)
    }

    #[inline]
    fn canon(val: i32) -> Self {
        DynamicModInt(if val < 0 { val + Self::modulus() } else { val })
    }

    #[inline]
    pub fn zero() -> Self {
        DynamicModInt(0)
    }

    #[inline]
    pub fn one() -> Self {
        DynamicModInt(1)
    }

    #[inline]
    pub fn two() -> Self {
        DynamicModInt(2)
    }

    pub fn pow(self, n: u64) -> Self {
        let mut n = n;
        let mut res = Self::one();
        let mut a = self;
        while n > 0 {
            if n & 1 == 1 {
                res = res * a;
            }
            a = a * a;
            n >>= 1;
        }

        res
    }

    pub fn inv(self) -> Self {
        self.pow(Self::modulus() as u64 - 2)
    }
}

macro_rules! from_bigger_int {
    ($($int:ident)*) => {$(
        impl From<$int> for DynamicModInt {
            fn from(val: $int) -> Self {
                Self::canon((val % Self::modulus() as $int) as i32)
            }
        }
    )*};
}
from_bigger_int!(u32 usize i64 u64 i128 u128);

macro_rules! from_smaller_int {
    ($($int: ident)*) => {$(
        impl From<$int> for DynamicModInt {
            fn from(val: $int) -> Self {
                Self::canon(val as i32 % Self::modulus())
            }
        }
    )*}
}
from_smaller_int!(i32 i16 u16 i8 u8);

impl Neg for DynamicModInt {
    type Output = Self;
    fn neg(self) -> Self {
        DynamicModInt(if self.0 == 0 {
            0
        } else {
            Self::modulus() - self.0
        })
    }
}

impl Add for DynamicModInt {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        let s = self.0 + other.0;
        let m = Self::modulus();
        DynamicModInt(if s >= m { s - m } else { s })
    }
}

impl Sub for DynamicModInt {
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        Self::canon(self.0 - other.0)
    }
}

impl Mul for DynamicModInt {
    type Output = Self;
    fn mul(self, other: Self) -> Self {
        let mul: u64 = (self.0 as u64 * other.0 as u64) % Self::modulus() as u64;
        DynamicModInt(mul as i32)
    }
}

impl Div for DynamicModInt {
    type Output = Self;
    fn div(self, other: Self) -> Self {
        self * other.inv()
    }
}

impl AddAssign for DynamicModInt {
    fn add_assign(&mut self, other: Self) {
        *self = *self + other;
    }
}

impl SubAssign for DynamicModInt {
    fn sub_assign(&mut self, other: Self) {
        *self = *self - other;
    }
}

impl MulAssign for DynamicModInt {
    fn mul_assign(&mut self, other: Self) {
        *self = *self * other;
    }
}

impl DivAssign for DynamicModInt {
    fn div_assign(&mut self, other: Self) {
        *self = *self / other;
    }
}

impl Sum for DynamicModInt {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        iter.fold(Self::zero(), Add::add)
    }
}

impl Product for DynamicModInt {
    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
        iter.fold(Self::one(), Mul::mul)
    }
}
// }}}


pub mod pr {
    #[inline(always)]
    #[allow(dead_code)]
    pub fn ln<T: std::fmt::Display>(x: T) {
        print!("{}\n", x)
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn e<T: std::fmt::Display>(x: T) {
        print!("{} ", x)
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn pb() {
        print!(" ")
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn endl() {
        print!("\n")
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn slice<T: std::fmt::Display>(v: &[T]) {
        for x in v {
            print!("{} ", &x);
        }
        print!("\n")
    }
}
pub mod algo {
    pub fn calculate_array_inversions<T: std::cmp::PartialOrd + Copy + Ord>(arr: &[T]) -> i64 {
        let (answer, _) = _calculate_array_inversions(arr);
        return answer;
    }
    fn _calculate_array_inversions<T: std::cmp::PartialOrd + Copy + Ord>(
        arr: &[T],
    ) -> (i64, Vec<T>) {
        let n = arr.len();
        match n {
            0 | 1 => return (0, arr.to_vec()),
            3..=10 => return _calculate_array_inversions_brute_force(arr),
            _ => (),
        }
        let mid = n / 2;
        let left = &arr[0..mid];
        let right = &arr[mid..];
        let (left_val, left_sorted) = _calculate_array_inversions(left);
        let (right_val, right_sorted) = _calculate_array_inversions(right);
        let (swap_count, vec_sorted) = _merge_sorted_vecs(left_sorted, right_sorted);
        let answer = left_val + right_val + swap_count;
        return (answer, vec_sorted);
    }
    fn _merge_sorted_vecs<T: std::cmp::PartialOrd + Copy + Ord>(
        left: Vec<T>,
        right: Vec<T>,
    ) -> (i64, Vec<T>) {
        assert!(!left.is_empty());
        assert!(!right.is_empty());
        let mut sorted = Vec::with_capacity(left.len() + right.len());
        let mut swap_count = 0;
        let mut lp: usize = 0;
        let mut rp: usize = 0;
        while lp < left.len() && rp < right.len() {
            match left[lp] <= right[rp] {
                true => {
                    sorted.push(left[lp]);
                    lp += 1;
                }
                false => {
                    sorted.push(right[rp]);
                    rp += 1;
                    let left_remained = left.len() - lp;
                    swap_count += left_remained as i64;
                }
            }
        }
        while lp < left.len() {
            sorted.push(left[lp]);
            lp += 1;
        }
        while rp < right.len() {
            sorted.push(right[rp]);
            rp += 1;
        }
        assert_eq!(sorted.len(), left.len() + right.len());
        assert_eq!(left.len(), lp);
        assert_eq!(right.len(), rp);
        return (swap_count, sorted);
    }
    fn _calculate_array_inversions_brute_force<T: std::cmp::PartialOrd + Copy + Ord>(
        arr: &[T],
    ) -> (i64, Vec<T>) {
        let n = arr.len();
        let mut answer = 0;
        for i in 0..n {
            for j in i + 1..n {
                if arr[i] > arr[j] {
                    answer += 1;
                }
            }
        }
        let mut v = arr.to_vec();
        v.sort_unstable();
        return (answer, v);
    }
    #[allow(dead_code)]
    pub fn find_max_min_pos<T: std::cmp::PartialOrd + Copy>(slice: &[T]) -> (T, T, usize, usize) {
        std::assert!(slice.len() > 0);
        let mut max = &slice[0];
        let mut min = &slice[0];
        let mut max_pos: usize = 0;
        let mut min_pos: usize = 0;
        for index in 1..slice.len() {
            if slice[index] < *min {
                min = &slice[index];
                min_pos = index;
            }
            if slice[index] > *max {
                max = &slice[index];
                max_pos = index;
            }
        }
        (*max, *min, max_pos, min_pos)
    }
}
pub mod nd {
    pub struct Arr<T> {
        _max_n: usize,
        _max_m: usize,
        _data: Vec<T>,
    }
    impl<T: Copy> Arr<T> {
        pub fn new(size: (usize, usize), default: T) -> Self {
            let dimensions = 2;
            let container_size = (size.0 + 1) * (size.1 + 1) + 1;
            let mut v = Vec::with_capacity(container_size);
            for _ in 0..container_size {
                v.push(default);
            }
            Arr {
                _max_n: size.0,
                _max_m: size.1,
                _data: v,
            }
        }
        fn _get_pos(&self, n: usize, m: usize) -> usize {
            assert!(n <= self._max_n);
            assert!(m <= self._max_m);
            n * self._max_m + m
        }
        pub fn get(&self, n: usize, m: usize) -> T {
            let p = self._get_pos(n, m);
            self._data[p]
        }
        pub fn set(&mut self, n: usize, m: usize, ans: T) -> T {
            let p = self._get_pos(n, m);
            self._data[p] = ans;
            ans
        }
    }
    impl<T: std::fmt::Display + Copy> std::fmt::Debug for Arr<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "Dim={}, ({},{})\n", 2, self._max_n, self._max_m);
            for i in 0..self._max_n {
                write!(f, "    [");
                for j in 0..self._max_m {
                    write!(f, "{}", self.get(i, j));
                    if j + 1 < self._max_m {
                        write!(f, ",");
                    }
                }
                write!(f, "]\n");
            }
            write!(f, "")
        }
    }
}
pub mod multi_queue {
    use std::collections::HashMap;
    use std::collections::VecDeque;
    pub struct MultiQueue<KeyT, ValT>
    where
        KeyT: Eq + std::hash::Hash,
    {
        _data: HashMap<KeyT, VecDeque<ValT>>,
    }
    impl<KeyT: Eq + std::hash::Hash, ValT> MultiQueue<KeyT, ValT> {
        pub fn new() -> Self {
            MultiQueue {
                _data: HashMap::new(),
            }
        }
        pub fn push(&mut self, key: KeyT, value: ValT) {
            let mut entry = self._data.entry(key).or_insert(VecDeque::new());
            entry.push_back(value);
        }
        #[doc = " Return None if 1. key not found 2. queue consumed"]
        pub fn pop(&mut self, key: KeyT) -> Option<ValT> {
            let mut queue = self._data.get_mut(&key);
            if queue.is_none() {
                return None;
            }
            let mut queue = queue.expect("Get Queue");
            queue.pop_front()
        }
    }
}
pub mod nums {
    #[doc = " Returns a vector representing the bits."]
    #[doc = "     i=63 is the highest bit, i=0 is the lowest bit"]
    #[doc = "     x = sigma v[i]*(2^i)"]
    #[doc = " # Arguments"]
    #[doc = ""]
    #[doc = " * `x`: A 64-bit number to be represented in bits"]
    #[doc = ""]
    #[doc = " returns: Vec<u8>"]
    #[doc = ""]
    #[allow(dead_code)]
    pub fn represent_into_bits(x: u64) -> Vec<u8> {
        let mut result = Vec::with_capacity(64);
        let mut x = x;
        for _ in 0..64 {
            let bit = x & 1;
            let bit = bit as u8;
            result.push(bit);
            x >>= 1;
        }
        assert_eq!(result.len(), 64);
        result
    }
    pub fn represent_from_bits(a: &Vec<u8>) -> u64 {
        assert_eq!(a.len(), 64);
        let mut result: u64 = 0;
        for i in 0..64 {
            result += a[i] as u64 * (1u64 << i);
        }
        result
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn multi_mod(x: i32, y: i32, modulo: i32) -> i32 {
        let mid: i64 = (x as i64) * (y as i64);
        let mid = mid % (modulo as i64);
        return mid as i32;
    }
    #[allow(dead_code)]
    pub fn pow_mod(base: i32, exp: u32, modulo: i32) -> i32 {
        let mut answer: i64 = 1;
        if exp > 10 {
            let sub_exp = exp / 2;
            let mut p: i64 = pow_mod(base, sub_exp, modulo) as i64;
            p = p as i64 * p as i64 % modulo as i64;
            if exp % 2 == 1 {
                p = p * base as i64 % modulo as i64;
            }
            return p as i32;
        }
        for _ in 0..exp {
            answer *= base as i64;
            answer %= modulo as i64;
        }
        answer as i32
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn in_closed_range(left: i32, right: i32, x: i32) -> bool {
        left <= x && x <= right
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn in_closed_range_reversible(left: i32, right: i32, x: i32) -> bool {
        match left.cmp(&right) {
            std::cmp::Ordering::Less => in_closed_range(left, right, x),
            std::cmp::Ordering::Equal => x == left,
            std::cmp::Ordering::Greater => in_closed_range(right, left, x),
        }
    }
    pub fn select_lowest_kth_bit(x: u32, b: u32) -> u32 {
        let result = (x >> b) & 1;
        assert!(result == 0 || result == 1);
        result
    }
    #[allow(dead_code)]
    pub fn calc_combination_with_mod(a: i32, b: i32, modulo: i32) -> i32 {
        let mut num: i64 = 1;
        let mut den: i64 = 1;
        for i in 0..b {
            num = num * (a - i) as i64 % modulo as i64;
            den = den * (i + 1) as i64 % modulo as i64;
        }
        let answer = num * pow_mod(den as i32, modulo as u32 - 2, modulo) as i64;
        let answer = answer % modulo as i64;
        answer as i32
    }
}
pub mod iters {
    pub fn permutation_chars(s: &str) -> Vec<Vec<u8>> {
        return permutation(s.as_bytes());
    }
    pub fn permutation<T: Copy>(s: &[T]) -> Vec<Vec<T>> {
        assert!(s.len() > 0);
        let mut possibilities = 1;
        for i in 1..=s.len() {
            possibilities *= i;
        }
        permutation_dfs(s, &vec![false; s.len()])
    }
    fn permutation_dfs<T: Copy>(s: &[T], used: &Vec<bool>) -> Vec<Vec<T>> {
        assert_eq!(s.len(), used.len());
        let mut result_list = Vec::new();
        for pos in 0..s.len() {
            if used[pos] {
                continue;
            }
            let mut new_used = used.clone();
            new_used[pos] = true;
            let select = s[pos];
            let recursive_results = permutation_dfs(s, &new_used);
            if recursive_results.is_empty() {
                let mut r = Vec::with_capacity(s.len());
                r.push(select);
                result_list.push(r);
            } else {
                for v in recursive_results {
                    let mut r = v;
                    r.push(select);
                    result_list.push(r);
                }
            }
        }
        result_list
    }
}
use std::error;
use std::fmt;
use std::str::FromStr;
#[non_exhaustive]
#[derive(Debug, PartialEq)]
pub enum Error {
    MissingMatch,
    MissingClosingBrace,
    UnexpectedValue(u8, Option<u8>),
    InvalidUtf8(Vec<u8>),
    PartialUtf8(usize, Vec<u8>),
    Parse(String, &'static str),
}
impl error::Error for Error {}
impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use crate::Error::*;
        use std::str::from_utf8;
        match *self {
            InvalidUtf8(ref raw) => write!(f, "input was not valid utf8: {:?}", raw),
            Parse(ref s, arg) => write!(f, "could not parse {} as target type of {}", s, arg),
            UnexpectedValue(exp, act) => write!(
                f,
                "found value {:?} not matching the pattern value {}",
                act.map(|b| b as char),
                exp as char
            ),
            PartialUtf8(n, ref raw) => write!(
                f,
                "input was only partially valid utf8: \"{}\" followed by {:?}",
                from_utf8(&raw[..n]).unwrap(),
                &raw[n..]
            ),
            MissingMatch => write!(f, "Bad read! format string: did not contain {{}}"),
            MissingClosingBrace => write!(
                f,
                "found single open curly brace at the end of the format string"
            ),
        }
    }
}
pub fn match_next(expected: u8, iter: &mut dyn Iterator<Item = u8>) -> Result<(), Error> {
    let next = iter.next();
    if next != Some(expected) {
        return Err(Error::UnexpectedValue(expected, next));
    }
    Ok(())
}
pub fn parse_capture<T>(
    name: &'static str,
    next: Option<u8>,
    iter: &mut dyn Iterator<Item = u8>,
) -> Result<T, Error>
where
    T: FromStr,
    <T as FromStr>::Err: ::std::fmt::Debug,
{
    static WHITESPACES: &[u8] = b"\t\r\n ";
    let raw: Vec<u8> = match next {
        Some(c) => iter.take_while(|&ch| ch != c).collect(),
        None => iter
            .skip_while(|ch| WHITESPACES.contains(ch))
            .take_while(|ch| !WHITESPACES.contains(ch))
            .collect(),
    };
    match String::from_utf8(raw) {
        Ok(s) => FromStr::from_str(&s).map_err(|_| Error::Parse(s, name)),
        Err(e) => {
            let n = e.utf8_error().valid_up_to();
            let raw = e.into_bytes();
            if n == 0 {
                Err(Error::InvalidUtf8(raw))
            } else {
                Err(Error::PartialUtf8(n, raw))
            }
        }
    }
}
#[macro_export]
macro_rules ! try_read (() => { $ crate :: try_read ! ("{}") } ; ($ text : expr) => { { (|| -> std :: result :: Result < _ , $ crate :: Error > { let __try_read_var__ ; $ crate :: try_scan ! ($ text , __try_read_var__) ; Ok (__try_read_var__) }) () } } ; ($ text : expr , $ input : expr) => { { (|| -> std :: result :: Result < _ , $ crate :: Error > { let __try_read_var__ ; $ crate :: try_scan ! ($ input => $ text , __try_read_var__) ; Ok (__try_read_var__) }) () } } ;) ;
#[macro_export]
macro_rules ! try_scan (($ pattern : expr , $ ($ arg : expr) ,*) => { use :: std :: io :: Read ; $ crate :: try_scan ! (:: std :: io :: stdin () . bytes () . map (std :: result :: Result :: unwrap) => $ pattern , $ ($ arg) ,*) ; } ; ($ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { $ crate :: try_scan ! (@ impl question_mark ; $ input => $ pattern , $ ($ arg) ,*) } } ; (@ question_mark : $ ($ e : tt) +) => { { ($ ($ e) +) ? } } ; (@ unwrap : $ ($ e : tt) +) => { { ($ ($ e) +) . unwrap () } } ; (@ impl $ action : tt ; $ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { #! [allow (clippy :: try_err)] use $ crate :: { Error , match_next , parse_capture } ; let pattern : &'static str = $ pattern ; let stdin : & mut Iterator < Item = u8 > = & mut ($ input) ; let mut pattern = pattern . bytes () ; $ ($ arg = loop { match $ crate :: try_scan ! (@$ action : pattern . next () . ok_or (Error :: MissingMatch)) { b'{' => match $ crate :: try_scan ! (@$ action : pattern . next () . ok_or (Error :: MissingClosingBrace)) { b'{' => $ crate :: try_scan ! (@$ action : match_next (b'{' , stdin)) , b'}' => break $ crate :: try_scan ! (@$ action : parse_capture (stringify ! ($ arg) , pattern . next () , stdin)) , _ => return $ crate :: try_scan ! (@$ action : Err (Error :: MissingClosingBrace)) , } , c => $ crate :: try_scan ! (@$ action : match_next (c , stdin)) , } } ;) * for c in pattern { $ crate :: try_scan ! (@$ action : match_next (c , stdin)) } format_args ! ($ pattern , $ ($ arg) ,*) ; } } ;) ;
#[doc = " All text input is handled through this macro"]
#[macro_export]
macro_rules ! read (($ ($ arg : tt) *) => { $ crate :: try_read ! ($ ($ arg) *) . unwrap () } ;) ;
#[doc = " This macro allows to pass several variables so multiple values can be read"]
#[macro_export]
macro_rules ! scan (($ text : expr , $ ($ arg : expr) ,*) => { use :: std :: io :: Read ; $ crate :: scan ! (:: std :: io :: stdin () . bytes () . map (std :: result :: Result :: unwrap) => $ text , $ ($ arg) ,*) ; } ; ($ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { $ crate :: try_scan ! (@ impl unwrap ; $ input => $ pattern , $ ($ arg) ,*) } } ;) ;
#[inline(always)]
#[allow(dead_code)]
pub fn read_ivec(n: usize) -> Vec<i32> {
    let mut vec = Vec::with_capacity(n);
    for _ in 0..n {
        let x: i32 = read!();
        vec.push(x);
    }
    return vec;
}
#[inline]
#[allow(dead_code)]
pub fn read_ived_1(n: usize) -> Vec<i32> {
    let mut vec = Vec::with_capacity(n + 1);
    vec.push(0);
    for _ in 0..n {
        let x: i32 = read!();
        vec.push(x);
    }
    return vec;
}
#[inline(always)]
#[allow(dead_code)]
pub fn read_uvec(n: usize) -> Vec<u32> {
    let mut vec = Vec::with_capacity(n);
    for _ in 0..n {
        let x: u32 = read!();
        vec.push(x);
    }
    return vec;
}
const MODULO: i32 = 1_000_000_007;
fn solve() -> Option<i64> {
    let n = read!();
    let k = read!();
    if k == 0 {
        return Some(1);
    }
    if n == 1 {
        let ans = nums::pow_mod(2, k, MODULO);
        return Some(ans as i64);
    }
    let free_select_01 = nums::pow_mod(2, n, MODULO);
    let mut greater_or_equal_select_01: i64 = 0;
    for selected_1 in (0..=n).step_by(2) {
        let c = nums::calc_combination_with_mod(n as i32, selected_1 as i32, MODULO);
        greater_or_equal_select_01 += c as i64;
        greater_or_equal_select_01 %= MODULO as i64;
    }
    if n % 2 != 0 {
        greater_or_equal_select_01 += 1;
        greater_or_equal_select_01 %= MODULO as i64;
    }
    let answer = calc(
        n,
        k - 1,
        free_select_01,
        greater_or_equal_select_01 as i32,
        MODULO,
    );
    Some(answer)
}
fn calc(
    n: u32,
    bit: u32,
    free_select_01: i32,
    greater_or_equal_select_01: i32,
    modulo: i32,
) -> i64 {
    let mut answer: i64 = 0;
    if bit == 0 {
        return greater_or_equal_select_01 as i64;
    }
    if n % 2 == 0 {
        answer += nums::pow_mod(free_select_01, bit, modulo) as i64;
    }
    let x = greater_or_equal_select_01 as i64
        * calc(
            n,
            bit - 1,
            free_select_01,
            greater_or_equal_select_01,
            modulo,
        )
        % MODULO as i64;
    answer += x as i64;
    answer %= MODULO as i64;
    answer
}
fn main() {
    let testcases: i32 = read!();
    for _ in 0..testcases {
        solve_and_print();
    }
}
#[inline]
fn solve_and_print() {
    let answer = solve();
    match answer {
        None => (),
        _ => pr::ln(answer.unwrap()),
    }
}


pub mod pr {
    #[inline(always)]
    #[allow(dead_code)]
    pub fn ln<T: std::fmt::Display>(x: T) {
        print!("{}\n", x)
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn e<T: std::fmt::Display>(x: T) {
        print!("{} ", x)
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn pb() {
        print!(" ")
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn endl() {
        print!("\n")
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn slice<T: std::fmt::Display>(v: &[T]) {
        for x in v {
            print!("{} ", &x);
        }
        print!("\n")
    }
}
pub mod algo {
    pub fn calculate_array_inversions<T: std::cmp::PartialOrd + Copy + Ord>(arr: &[T]) -> i64 {
        let (answer, _) = _calculate_array_inversions(arr);
        return answer;
    }
    fn _calculate_array_inversions<T: std::cmp::PartialOrd + Copy + Ord>(
        arr: &[T],
    ) -> (i64, Vec<T>) {
        let n = arr.len();
        match n {
            0 | 1 => return (0, arr.to_vec()),
            3..=10 => return _calculate_array_inversions_brute_force(arr),
            _ => (),
        }
        let mid = n / 2;
        let left = &arr[0..mid];
        let right = &arr[mid..];
        let (left_val, left_sorted) = _calculate_array_inversions(left);
        let (right_val, right_sorted) = _calculate_array_inversions(right);
        let (swap_count, vec_sorted) = _merge_sorted_vecs(left_sorted, right_sorted);
        let answer = left_val + right_val + swap_count;
        return (answer, vec_sorted);
    }
    fn _merge_sorted_vecs<T: std::cmp::PartialOrd + Copy + Ord>(
        left: Vec<T>,
        right: Vec<T>,
    ) -> (i64, Vec<T>) {
        assert!(!left.is_empty());
        assert!(!right.is_empty());
        let mut sorted = Vec::with_capacity(left.len() + right.len());
        let mut swap_count = 0;
        let mut lp: usize = 0;
        let mut rp: usize = 0;
        while lp < left.len() && rp < right.len() {
            match left[lp] <= right[rp] {
                true => {
                    sorted.push(left[lp]);
                    lp += 1;
                }
                false => {
                    sorted.push(right[rp]);
                    rp += 1;
                    let left_remained = left.len() - lp;
                    swap_count += left_remained as i64;
                }
            }
        }
        while lp < left.len() {
            sorted.push(left[lp]);
            lp += 1;
        }
        while rp < right.len() {
            sorted.push(right[rp]);
            rp += 1;
        }
        assert_eq!(sorted.len(), left.len() + right.len());
        assert_eq!(left.len(), lp);
        assert_eq!(right.len(), rp);
        return (swap_count, sorted);
    }
    fn _calculate_array_inversions_brute_force<T: std::cmp::PartialOrd + Copy + Ord>(
        arr: &[T],
    ) -> (i64, Vec<T>) {
        let n = arr.len();
        let mut answer = 0;
        for i in 0..n {
            for j in i + 1..n {
                if arr[i] > arr[j] {
                    answer += 1;
                }
            }
        }
        let mut v = arr.to_vec();
        v.sort_unstable();
        return (answer, v);
    }
    #[allow(dead_code)]
    pub fn find_max_min_pos<T: std::cmp::PartialOrd + Copy>(slice: &[T]) -> (T, T, usize, usize) {
        std::assert!(slice.len() > 0);
        let mut max = &slice[0];
        let mut min = &slice[0];
        let mut max_pos: usize = 0;
        let mut min_pos: usize = 0;
        for index in 1..slice.len() {
            if slice[index] < *min {
                min = &slice[index];
                min_pos = index;
            }
            if slice[index] > *max {
                max = &slice[index];
                max_pos = index;
            }
        }
        (*max, *min, max_pos, min_pos)
    }
}
pub mod nd {
    pub struct Arr<T> {
        _max_n: usize,
        _max_m: usize,
        _data: Vec<T>,
    }
    impl<T: Copy> Arr<T> {
        pub fn new(size: (usize, usize), default: T) -> Self {
            let dimensions = 2;
            let container_size = (size.0 + 1) * (size.1 + 1) + 1;
            let mut v = Vec::with_capacity(container_size);
            for _ in 0..container_size {
                v.push(default);
            }
            Arr {
                _max_n: size.0,
                _max_m: size.1,
                _data: v,
            }
        }
        fn _get_pos(&self, n: usize, m: usize) -> usize {
            assert!(n <= self._max_n);
            assert!(m <= self._max_m);
            n * self._max_m + m
        }
        pub fn get(&self, n: usize, m: usize) -> T {
            let p = self._get_pos(n, m);
            self._data[p]
        }
        pub fn set(&mut self, n: usize, m: usize, ans: T) -> T {
            let p = self._get_pos(n, m);
            self._data[p] = ans;
            ans
        }
    }
    impl<T: std::fmt::Display + Copy> std::fmt::Debug for Arr<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "Dim={}, ({},{})\n", 2, self._max_n, self._max_m);
            for i in 0..self._max_n {
                write!(f, "    [");
                for j in 0..self._max_m {
                    write!(f, "{}", self.get(i, j));
                    if j + 1 < self._max_m {
                        write!(f, ",");
                    }
                }
                write!(f, "]\n");
            }
            write!(f, "")
        }
    }
}
pub mod multi_queue {
    use std::collections::HashMap;
    use std::collections::VecDeque;
    pub struct MultiQueue<KeyT, ValT>
    where
        KeyT: Eq + std::hash::Hash,
    {
        _data: HashMap<KeyT, VecDeque<ValT>>,
    }
    impl<KeyT: Eq + std::hash::Hash, ValT> MultiQueue<KeyT, ValT> {
        pub fn new() -> Self {
            MultiQueue {
                _data: HashMap::new(),
            }
        }
        pub fn push(&mut self, key: KeyT, value: ValT) {
            let mut entry = self._data.entry(key).or_insert(VecDeque::new());
            entry.push_back(value);
        }
        #[doc = " Return None if 1. key not found 2. queue consumed"]
        pub fn pop(&mut self, key: KeyT) -> Option<ValT> {
            let mut queue = self._data.get_mut(&key);
            if queue.is_none() {
                return None;
            }
            let mut queue = queue.expect("Get Queue");
            queue.pop_front()
        }
    }
}
pub mod nums {
    #[doc = " Returns a vector representing the bits."]
    #[doc = "     i=63 is the highest bit, i=0 is the lowest bit"]
    #[doc = "     x = sigma v[i]*(2^i)"]
    #[doc = " # Arguments"]
    #[doc = ""]
    #[doc = " * `x`: A 64-bit number to be represented in bits"]
    #[doc = ""]
    #[doc = " returns: Vec<u8>"]
    #[doc = ""]
    #[allow(dead_code)]
    pub fn represent_into_bits(x: u64) -> Vec<u8> {
        let mut result = Vec::with_capacity(64);
        let mut x = x;
        for _ in 0..64 {
            let bit = x & 1;
            let bit = bit as u8;
            result.push(bit);
            x >>= 1;
        }
        assert_eq!(result.len(), 64);
        result
    }
    pub fn represent_from_bits(a: &Vec<u8>) -> u64 {
        assert_eq!(a.len(), 64);
        let mut result: u64 = 0;
        for i in 0..64 {
            result += a[i] as u64 * (1u64 << i);
        }
        result
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn multi_mod(x: i32, y: i32, modulo: i32) -> i32 {
        let mid: i64 = (x as i64) * (y as i64);
        let mid = mid % (modulo as i64);
        return mid as i32;
    }
    #[allow(dead_code)]
    pub fn pow_mod(base: i32, exp: u32, modulo: i32) -> i32 {
        let mut answer: i64 = 1;
        if exp > 10 {
            let sub_exp = exp / 2;
            let mut p: i64 = pow_mod(base, sub_exp, modulo) as i64;
            p = p as i64 * p as i64 % modulo as i64;
            if exp % 2 == 1 {
                p = p * base as i64 % modulo as i64;
            }
            return p as i32;
        }
        for _ in 0..exp {
            answer *= base as i64;
            answer %= modulo as i64;
        }
        answer as i32
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn in_closed_range(left: i32, right: i32, x: i32) -> bool {
        left <= x && x <= right
    }
    #[inline(always)]
    #[allow(dead_code)]
    pub fn in_closed_range_reversible(left: i32, right: i32, x: i32) -> bool {
        match left.cmp(&right) {
            std::cmp::Ordering::Less => in_closed_range(left, right, x),
            std::cmp::Ordering::Equal => x == left,
            std::cmp::Ordering::Greater => in_closed_range(right, left, x),
        }
    }
    pub fn select_lowest_kth_bit(x: u32, b: u32) -> u32 {
        let result = (x >> b) & 1;
        assert!(result == 0 || result == 1);
        result
    }
    #[allow(dead_code)]
    pub fn calc_combination_with_mod(a: i32, b: i32, modulo: i32) -> i32 {
        let mut num: i64 = 1;
        let mut den: i64 = 1;
        for i in 0..b {
            num = num * (a - i) as i64 % modulo as i64;
            den = den * (i + 1) as i64 % modulo as i64;
        }
        let answer = num * pow_mod(den as i32, modulo as u32 - 2, modulo) as i64;
        let answer = answer % modulo as i64;
        answer as i32
    }
}
pub mod iters {
    pub fn permutation_chars(s: &str) -> Vec<Vec<u8>> {
        return permutation(s.as_bytes());
    }
    pub fn permutation<T: Copy>(s: &[T]) -> Vec<Vec<T>> {
        assert!(s.len() > 0);
        let mut possibilities = 1;
        for i in 1..=s.len() {
            possibilities *= i;
        }
        permutation_dfs(s, &vec![false; s.len()])
    }
    fn permutation_dfs<T: Copy>(s: &[T], used: &Vec<bool>) -> Vec<Vec<T>> {
        assert_eq!(s.len(), used.len());
        let mut result_list = Vec::new();
        for pos in 0..s.len() {
            if used[pos] {
                continue;
            }
            let mut new_used = used.clone();
            new_used[pos] = true;
            let select = s[pos];
            let recursive_results = permutation_dfs(s, &new_used);
            if recursive_results.is_empty() {
                let mut r = Vec::with_capacity(s.len());
                r.push(select);
                result_list.push(r);
            } else {
                for v in recursive_results {
                    let mut r = v;
                    r.push(select);
                    result_list.push(r);
                }
            }
        }
        result_list
    }
}
use std::error;
use std::fmt;
use std::str::FromStr;
#[non_exhaustive]
#[derive(Debug, PartialEq)]
pub enum Error {
    MissingMatch,
    MissingClosingBrace,
    UnexpectedValue(u8, Option<u8>),
    InvalidUtf8(Vec<u8>),
    PartialUtf8(usize, Vec<u8>),
    Parse(String, &'static str),
}
impl error::Error for Error {}
impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use crate::Error::*;
        use std::str::from_utf8;
        match *self {
            InvalidUtf8(ref raw) => write!(f, "input was not valid utf8: {:?}", raw),
            Parse(ref s, arg) => write!(f, "could not parse {} as target type of {}", s, arg),
            UnexpectedValue(exp, act) => write!(
                f,
                "found value {:?} not matching the pattern value {}",
                act.map(|b| b as char),
                exp as char
            ),
            PartialUtf8(n, ref raw) => write!(
                f,
                "input was only partially valid utf8: \"{}\" followed by {:?}",
                from_utf8(&raw[..n]).unwrap(),
                &raw[n..]
            ),
            MissingMatch => write!(f, "Bad read! format string: did not contain {{}}"),
            MissingClosingBrace => write!(
                f,
                "found single open curly brace at the end of the format string"
            ),
        }
    }
}
pub fn match_next(expected: u8, iter: &mut dyn Iterator<Item = u8>) -> Result<(), Error> {
    let next = iter.next();
    if next != Some(expected) {
        return Err(Error::UnexpectedValue(expected, next));
    }
    Ok(())
}
pub fn parse_capture<T>(
    name: &'static str,
    next: Option<u8>,
    iter: &mut dyn Iterator<Item = u8>,
) -> Result<T, Error>
where
    T: FromStr,
    <T as FromStr>::Err: ::std::fmt::Debug,
{
    static WHITESPACES: &[u8] = b"\t\r\n ";
    let raw: Vec<u8> = match next {
        Some(c) => iter.take_while(|&ch| ch != c).collect(),
        None => iter
            .skip_while(|ch| WHITESPACES.contains(ch))
            .take_while(|ch| !WHITESPACES.contains(ch))
            .collect(),
    };
    match String::from_utf8(raw) {
        Ok(s) => FromStr::from_str(&s).map_err(|_| Error::Parse(s, name)),
        Err(e) => {
            let n = e.utf8_error().valid_up_to();
            let raw = e.into_bytes();
            if n == 0 {
                Err(Error::InvalidUtf8(raw))
            } else {
                Err(Error::PartialUtf8(n, raw))
            }
        }
    }
}
#[macro_export]
macro_rules ! try_read (() => { $ crate :: try_read ! ("{}") } ; ($ text : expr) => { { (|| -> std :: result :: Result < _ , $ crate :: Error > { let __try_read_var__ ; $ crate :: try_scan ! ($ text , __try_read_var__) ; Ok (__try_read_var__) }) () } } ; ($ text : expr , $ input : expr) => { { (|| -> std :: result :: Result < _ , $ crate :: Error > { let __try_read_var__ ; $ crate :: try_scan ! ($ input => $ text , __try_read_var__) ; Ok (__try_read_var__) }) () } } ;) ;
#[macro_export]
macro_rules ! try_scan (($ pattern : expr , $ ($ arg : expr) ,*) => { use :: std :: io :: Read ; $ crate :: try_scan ! (:: std :: io :: stdin () . bytes () . map (std :: result :: Result :: unwrap) => $ pattern , $ ($ arg) ,*) ; } ; ($ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { $ crate :: try_scan ! (@ impl question_mark ; $ input => $ pattern , $ ($ arg) ,*) } } ; (@ question_mark : $ ($ e : tt) +) => { { ($ ($ e) +) ? } } ; (@ unwrap : $ ($ e : tt) +) => { { ($ ($ e) +) . unwrap () } } ; (@ impl $ action : tt ; $ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { #! [allow (clippy :: try_err)] use $ crate :: { Error , match_next , parse_capture } ; let pattern : &'static str = $ pattern ; let stdin : & mut Iterator < Item = u8 > = & mut ($ input) ; let mut pattern = pattern . bytes () ; $ ($ arg = loop { match $ crate :: try_scan ! (@$ action : pattern . next () . ok_or (Error :: MissingMatch)) { b'{' => match $ crate :: try_scan ! (@$ action : pattern . next () . ok_or (Error :: MissingClosingBrace)) { b'{' => $ crate :: try_scan ! (@$ action : match_next (b'{' , stdin)) , b'}' => break $ crate :: try_scan ! (@$ action : parse_capture (stringify ! ($ arg) , pattern . next () , stdin)) , _ => return $ crate :: try_scan ! (@$ action : Err (Error :: MissingClosingBrace)) , } , c => $ crate :: try_scan ! (@$ action : match_next (c , stdin)) , } } ;) * for c in pattern { $ crate :: try_scan ! (@$ action : match_next (c , stdin)) } format_args ! ($ pattern , $ ($ arg) ,*) ; } } ;) ;
#[doc = " All text input is handled through this macro"]
#[macro_export]
macro_rules ! read (($ ($ arg : tt) *) => { $ crate :: try_read ! ($ ($ arg) *) . unwrap () } ;) ;
#[doc = " This macro allows to pass several variables so multiple values can be read"]
#[macro_export]
macro_rules ! scan (($ text : expr , $ ($ arg : expr) ,*) => { use :: std :: io :: Read ; $ crate :: scan ! (:: std :: io :: stdin () . bytes () . map (std :: result :: Result :: unwrap) => $ text , $ ($ arg) ,*) ; } ; ($ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { $ crate :: try_scan ! (@ impl unwrap ; $ input => $ pattern , $ ($ arg) ,*) } } ;) ;
#[inline(always)]
#[allow(dead_code)]
pub fn read_ivec(n: usize) -> Vec<i32> {
    let mut vec = Vec::with_capacity(n);
    for _ in 0..n {
        let x: i32 = read!();
        vec.push(x);
    }
    return vec;
}
#[inline]
#[allow(dead_code)]
pub fn read_ived_1(n: usize) -> Vec<i32> {
    let mut vec = Vec::with_capacity(n + 1);
    vec.push(0);
    for _ in 0..n {
        let x: i32 = read!();
        vec.push(x);
    }
    return vec;
}
#[inline(always)]
#[allow(dead_code)]
pub fn read_uvec(n: usize) -> Vec<u32> {
    let mut vec = Vec::with_capacity(n);
    for _ in 0..n {
        let x: u32 = read!();
        vec.push(x);
    }
    return vec;
}
const MODULO: i32 = 1_000_000_007;
fn solve() -> Option<i64> {
    let n = read!();
    let k = read!();
    if k == 0 {
        return Some(1);
    }
    if n == 1 {
        let ans = nums::pow_mod(2, k, MODULO);
        return Some(ans as i64);
    }
    let free_select_01 = nums::pow_mod(2, n, MODULO);
    let mut factorial = vec![1i64; n as usize + 1];
    for i in 1usize..=(n as usize) {
        factorial[i] = factorial[i - 1] * i as i64;
        factorial[i] %= MODULO as i64;
    }
    let mut greater_or_equal_select_01: i64 = 0;
    for selected_1 in (0..=n as usize).step_by(2) {
        let a = factorial[n as usize];
        let b = factorial[n as usize - selected_1];
        let b = nums::pow_mod(b as i32, MODULO as u32 - 2, MODULO);
        let b2 = factorial[selected_1];
        let b2 = nums::pow_mod(b2 as i32, MODULO as u32 - 2, MODULO);
        let c = a * b as i64 % MODULO as i64 * b2 as i64 % MODULO as i64;
        greater_or_equal_select_01 += c as i64;
        greater_or_equal_select_01 %= MODULO as i64;
    }
    if n % 2 != 0 {
        greater_or_equal_select_01 += 1;
        greater_or_equal_select_01 %= MODULO as i64;
    }
    let mut answer: i64 = greater_or_equal_select_01 as i64;
    let mut prev: i64 = 0;
    let mut pow_bit = 1 as i64;
    for bit in 1..k {
        prev = answer;
        answer = 0;
        let x = greater_or_equal_select_01 as i64 * prev % MODULO as i64;
        answer += x as i64;
        answer %= MODULO as i64;
        if n % 2 == 0 {
            pow_bit *= free_select_01 as i64;
            pow_bit %= MODULO as i64;
            answer += pow_bit;
            answer -= prev;
            answer %= MODULO as i64;
        }
    }
    Some(answer)
}
fn calc(
    n: u32,
    bit: u32,
    free_select_01: i32,
    greater_or_equal_select_01: i32,
    modulo: i32,
) -> i64 {
    let mut answer: i64 = 0;
    if bit == 0 {
        return greater_or_equal_select_01 as i64;
    }
    if n % 2 == 0 {
        answer += nums::pow_mod(free_select_01, bit, modulo) as i64;
    }
    let x = greater_or_equal_select_01 as i64
        * calc(
            n,
            bit - 1,
            free_select_01,
            greater_or_equal_select_01,
            modulo,
        )
        % MODULO as i64;
    answer += x as i64;
    answer %= MODULO as i64;
    answer
}
fn main() {
    let testcases: i32 = read!();
    for _ in 0..testcases {
        solve_and_print();
    }
}
#[inline]
fn solve_and_print() {
    let answer = solve();
    match answer {
        None => (),
        _ => pr::ln(answer.unwrap()),
    }
}


#![allow(non_snake_case)]

use std::io::{self, prelude::*};

fn solve<B: BufRead, W: Write>(scn: &mut Scanner<B>, wrt: &mut W) {
    let MOD: u64 = 1000000000+7;

    let N = scn.token::<u64>();
    let K = scn.token();

    let pw = |b: u64, mut a: u64| {
        let mut res = 1;
        let mut p = b;
        while a > 0 {
            if a & 1 == 1 {
                res = (res * p) % MOD;
            }
            p = (p*p) % MOD;
            a >>= 1;
        }
        res
    };

    let mut ans = 0;
    let mut dw = 1;

    for i in 0..K {
        if N & 1 == 0 {
            //auto win here and n even
            ans = (ans + ((dw * pw(2, K-i-1)) % MOD)) % MOD;
            dw = (dw * (pw(2, N-1) - 1)) % MOD;
        } else {
            //n odd
            dw = ((dw * (pw(2, N-1) + 1)) % MOD) % MOD;
        }
    }

    ans = (ans + dw) % MOD;

    writeln!(wrt, "{}", ans).unwrap();
}

fn main() {
    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut reader = Scanner::new(stdin.lock());
    let mut writer = io::BufWriter::new(stdout.lock());

    let T = reader.token::<usize>();
    //let T = 1;
    for _ in 0..T {
        solve(&mut reader, &mut writer);
    }
}

pub struct Scanner<B> {
    reader: B,
    buf_str: Vec<u8>,
    buf_iter: std::str::SplitWhitespace<'static>,
}

impl<B: BufRead> Scanner<B> {
    pub fn new(reader: B) -> Self {
        Self {
            reader,
            buf_str: Vec::new(),
            buf_iter: "".split_whitespace(),
        }
    }
    pub fn token<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = std::str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_whitespace())
            }
        }
    }
}


// ---------- 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 = 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 ----------
// ---------- begin Precalc ----------
mod precalc {
    use super::modint::*;
    #[allow(dead_code)]
    pub struct Precalc<T> {
        inv: Vec<ModInt<T>>,
        fact: Vec<ModInt<T>>,
        ifact: Vec<ModInt<T>>,
    }
    #[allow(dead_code)]
    impl<T: Modulo> Precalc<T> {
        pub fn new(n: usize) -> Precalc<T> {
            let mut inv = vec![ModInt::one(); n + 1];
            let mut fact = vec![ModInt::one(); n + 1];
            let mut ifact = vec![ModInt::one(); n + 1];
            for i in 2..(n + 1) {
                fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);
            }
            ifact[n] = fact[n].inv();
            if n > 0 {
                inv[n] = ifact[n] * fact[n - 1];
            }
            for i in (1..n).rev() {
                ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);
                inv[i] = ifact[i] * fact[i - 1];
            }
            Precalc {
                inv: inv,
                fact: fact,
                ifact: ifact,
            }
        }
        pub fn inv(&self, n: usize) -> ModInt<T> {
            assert!(n > 0);
            self.inv[n]
        }
        pub fn fact(&self, n: usize) -> ModInt<T> {
            self.fact[n]
        }
        pub fn ifact(&self, n: usize) -> ModInt<T> {
            self.ifact[n]
        }
        pub fn perm(&self, n: usize, k: usize) -> ModInt<T> {
            if k > n {
                return ModInt::zero();
            }
            self.fact[n] * self.ifact[n - k]
        }
        pub fn comb(&self, n: usize, k: usize) -> ModInt<T> {
            if k > n {
                return ModInt::zero();
            }
            self.fact[n] * self.ifact[k] * self.ifact[n - k]
        }
    }
}
// ---------- end Precalc ----------

use modint::*;

type M = ModInt<Mod1_000_000_007>;

// ---------- 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 std::io::Write;
use std::collections::*;

type Map<K, V> = BTreeMap<K, V>;
type Set<T> = BTreeSet<T>;
type Deque<T> = VecDeque<T>;

fn run() {
    input! {
        t: usize,
        ask: [(usize, usize); t],
    }
    for (n, k) in ask {
        let mut ans = M::zero();
        let mut even = M::one();
        for i in 0..k {
            if n % 2 == 1 {
                ans += even * M::new(2).pow((k - 1 - i) as u64 * n as u64);
            }
            even *= M::new(2).pow((n - 1) as u64);
        }
        ans += even;
        println!("{}", ans);
    }
}

fn main() {
    run();
}