#![allow(dead_code, unused_macros, unused_imports)]
use std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::{TryInto, TryFrom}, marker::PhantomData};

const IO_BUF_SIZE: usize = 1 << 16;
type Input = Scanner<Stdin>;
type Output = BufWriter<Stdout>;
fn _init_input() -> Input { Scanner::new(std::io::stdin()) }
fn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }

#[repr(transparent)] struct Unsync<T>(T);
unsafe impl<T> Sync for Unsync<T> {}

type BadLazy<T> = Unsync<UnsafeCell<Option<T>>>;
impl<T> BadLazy<T> {
    const fn new() -> Self { Self(UnsafeCell::new(None)) }
}

static INPUT: BadLazy<Input> = BadLazy::new();
static OUTPUT: BadLazy<Output> = BadLazy::new();

fn inp<F: FnOnce(&mut Input) -> R, R>(f: F) -> R {
    unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }
}
fn out<F: FnOnce(&mut Output) -> R, R>(f: F) -> R {
    unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }
}

macro_rules! read {
    () => { read() };
    ($t: ty) => { read::<$t>() };
    ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };
    [$t: ty; $n: expr] => { read_vec::<$t>($n) };
}
macro_rules! println {
    () => { out(|x| { let _ = writeln!(x); }) };
    ($exp: expr) => { out(|x| { let _ = writeln!(x, "{}", $exp); }) };
    ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }
}
macro_rules! print {
    ($exp: expr) => { out(|x| { let _ = write!(x, "{}", $exp); }) };
    ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }
}

fn out_flush() { out(|x| { let _ = x.flush(); }); }

fn input_is_eof() -> bool { inp(|x| x.eof()) }
fn read_byte() -> u8 { inp(|x| x.byte()) }
fn read_bytes_no_skip(n: usize) -> Vec<u8> { inp(|x| x.bytes_no_skip(n)) }
fn read_bytes(n: usize) -> Vec<u8> { inp(|x| x.bytes(n)) }
fn read_bytes2(n: usize, m: usize) -> Vec<Vec<u8>> { inp(|x| x.bytes2(n, m)) }
fn read_token() -> Vec<u8> { inp(|x| x.token_bytes()) }
fn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }
fn read_line() -> Vec<u8> { inp(|x| x.line_bytes()) }
fn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }
fn read<T: FromStr>() -> T { read_token_str().parse::<T>().ok().expect("failed parse") }
fn read_vec<T: FromStr>(n: usize) -> Vec<T> { (0..n).map(|_| read()).collect() }
fn read_vec2<T: FromStr>(n: usize, m: usize) -> Vec<Vec<T>> { (0..n).map(|_| read_vec(m)).collect() }

struct Scanner<R: Read> {
    src: R,
    _buf: Vec<u8>,
    _pt: usize, // pointer
    _rd: usize, // bytes read
}

#[allow(dead_code)]
impl<R: Read> Scanner<R> {
    fn new(src: R) -> Scanner<R> {
        Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }
    }

    fn _check_buf(&mut self) {
        if self._pt == self._rd {
            self._rd = self.src.read(&mut self._buf).unwrap_or(0);
            self._pt = (self._rd == 0) as usize;
        }
    }

    // returns true if end of file
    fn eof(&mut self) -> bool {
        self._check_buf();
        self._rd == 0
    }

    // filters \r, returns \0 if eof
    fn byte(&mut self) -> u8 {
        loop {
            self._check_buf();
            if self._rd == 0 { return 0; }
            let res = self._buf[self._pt];
            self._pt += 1;
            if res != b'\r' { return res; }
        }
    }

    fn bytes_no_skip(&mut self, n: usize) -> Vec<u8> { (0..n).map(|_| self.byte()).collect() }
    fn bytes(&mut self, n: usize) -> Vec<u8> {
        let res = self.bytes_no_skip(n);
        self.byte();
        res
    }
    fn bytes2(&mut self, n: usize, m: usize) -> Vec<Vec<u8>> { (0..n).map(|_| self.bytes(m)).collect() }

    fn token_bytes(&mut self) -> Vec<u8> {
        let mut res = Vec::new();
        let mut c = self.byte();
        while c <= b' ' {
            if c == b'\0' { return res; }
            c = self.byte();
        }
        loop {
            res.push(c);
            c = self.byte();
            if c <= b' ' { return res; }
        }
    }

    fn line_bytes(&mut self) -> Vec<u8> {
        let mut res = Vec::new();
        let mut c = self.byte();
        while c != b'\n' && c != b'\0' {
            res.push(c);
            c = self.byte();
        }
        res
    }
}

trait JoinToStr {
    fn join_to_str(self, sep: &str) -> String;
    fn concat_to_str(self) -> String;
}
impl<T: Display, I: Iterator<Item = T>> JoinToStr for I {
    fn join_to_str(mut self, sep: &str) -> String {
        match self.next() {
            Some(first) => {
                let mut res = first.to_string();
                while let Some(item) = self.next() {
                    res.push_str(sep);
                    res.push_str(&item.to_string());
                }
                res
            }
            None => { String::new() }
        }
    }

    fn concat_to_str(self) -> String {
        let mut res = String::new();
        for item in self { res.push_str(&item.to_string()); }
        res
    }
}
trait AsStr { fn as_str(&self) -> &str; }
impl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect("attempt to convert non-UTF8 byte string.")} }

macro_rules! veci {
    ($n:expr , $i:ident : $gen:expr) => {{
        let _veci_n = $n;
        let mut _veci_list = Vec::with_capacity(_veci_n);
        for $i in 0.._veci_n {
            _veci_list.push($gen);
        }
        _veci_list
    }};
    ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }
}

fn abs_diff<T: Sub<Output = T> + PartialOrd>(x: T, y: T) -> T {
    if x < y { y - x } else { x - y }
}

trait CommonNumExt {
    fn div_ceil(self, b: Self) -> Self;
    fn div_floor(self, b: Self) -> Self;
    fn gcd(self, b: Self) -> Self;
    fn highest_one(self) -> Self;
    fn lowest_one(self) -> Self;
    fn sig_bits(self) -> u32;
}

macro_rules! impl_common_num_ext {
    ($($ix:tt = $ux:tt),*) => {
        $(
            impl CommonNumExt for $ux {
                fn div_ceil(self, b: Self) -> Self {
                    let q = self / b; let r = self % b;
                    if r != 0 { q + 1 } else { q }
                }
                fn div_floor(self, b: Self) -> Self { self / b }
                fn gcd(self, mut b: Self) -> Self {
                    let mut a = self;
                    if a == 0 || b == 0 { return a | b; }
                    let shift = (a | b).trailing_zeros();
                    a >>= a.trailing_zeros();
                    b >>= b.trailing_zeros();
                    while a != b {
                        if a > b { a -= b; a >>= a.trailing_zeros(); }
                        else { b -= a; b >>= b.trailing_zeros(); }
                    }
                    a << shift
                }
                #[inline] fn highest_one(self) -> Self {
                    if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 }
                }
                #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }
                #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }
            }

            impl CommonNumExt for $ix {
                fn div_ceil(self, b: Self) -> Self {
                    let q = self / b; let r = self % b;
                    if self ^ b >= 0 && r != 0 { q + 1 } else { q }
                }
                fn div_floor(self, b: Self) -> Self {
                    let q = self / b; let r = self % b;
                    if self ^ b < 0 && r != 0 { q - 1 } else { q }
                }
                fn gcd(self, b: Self) -> Self {
                    fn w_abs(x: $ix) -> $ux { (if x.is_negative() { x.wrapping_neg() } else { x }) as _ }
                    w_abs(self).gcd(w_abs(b)) as _
                }
                #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }
                #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }
                #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }
            }
        )*
    }
}
impl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);

trait ChMaxMin<T> {
    fn chmax(&mut self, v: T) -> bool;
    fn chmin(&mut self, v: T) -> bool;
}
impl<T: PartialOrd> ChMaxMin<T> for Option<T> {
    fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }
    fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }
}
impl<T: PartialOrd> ChMaxMin<T> for T {
    fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }
    fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }
}

// * end commons * //

pub trait BinarySearchExt<T> {
    fn binary_search_by<F: FnMut(T) -> Ordering>(&self, f: F) -> Result<T, T>;

    fn partition_point<F: FnMut(T) -> bool>(&self, mut f: F) -> T {
        self.binary_search_by(|x| if f(x) { Ordering::Less } else { Ordering::Greater }).err().unwrap()
    }
}
macro_rules! impl_binary_search_ext_integer {
    ($($ty:tt),*) => {
        $(
            impl BinarySearchExt<$ty> for std::ops::Range<$ty> {
                fn binary_search_by<F: FnMut($ty) -> Ordering>(&self, mut f: F) -> Result<$ty, $ty> {
                    let mut low = self.start;
                    let mut high = self.end;

                    while low < high {
                        let mid = (low & high) + ((low ^ high) >> 1);
                        let cmp = f(mid);
                        if cmp == Ordering::Less {
                            low = mid + 1;
                        } else if cmp == Ordering::Greater {
                            high = mid;
                        } else {
                            return Ok(mid);
                        }
                    }
                    Err(low)
                }
            }
        )*
    }
}
impl_binary_search_ext_integer!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);

#[allow(non_snake_case, non_upper_case_globals)]
fn main() {
    let num_cases: usize = 1;//read();

    for _case_num in 1..=num_cases {
		let n = read!(u32);

		let ans = (3..2*n+2).partition_point(|x| x.saturating_sub(1) / 2 + x.saturating_sub(4) / 4 < n);
		println!(ans);
    }

    out_flush();
}


use std::io::{self, Read};
use std::cmp::min;

fn read_line() -> Vec<i32> {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    return buf.trim().split(" ")
        .map(|x| {x.parse::<i32>().unwrap() })
        .collect();
}

fn get_ans (a : i32, b : i32, c : i32, d : i32) -> i32{
    let ans = -1;

    for i in 0..101{
        for j in 0..101{
            if (a*i + b == c*j + d){
                return a*i + b;
            }
        }
    }

    return 0x3f3f3f3f;
}

fn main(){
    let mut line = read_line();
    let (a, b) = (line[0], line[1]);
    line = read_line();
    let (c, d) = (line[0], line[1]);

    let mut ans = 0x3f3f3f3f;

    ans = min (get_ans(c, d, a, b), get_ans(a, b, c, d));
    if (ans == 0x3f3f3f3f){
        println! ("-1");
    }
    else{
        println! ("{}", ans);
    }

}


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

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

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

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

fn extended_euclid(a: i32, b: i32) -> (i32, i32, i32) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (d, x, y) = extended_euclid(b, modulo(a, b));
        (d, y, x - a / b * y)
    }
}

fn modulo(a: i32, b: i32) -> i32 {
    let ret_val = a % b;
    if ret_val < 0 {
        ret_val + b
    } else {
        ret_val
    }
}

fn main() {
    let (a, b): (i32, i32) = {
        let input = get_line();
        let mut it = input.split_whitespace().map(|k| k.parse().unwrap());
        (
            it.next().unwrap(),
            it.next().unwrap(),
            )
    };

    let (c, d): (i32, i32) = {
        let input = get_line();
        let mut it = input.split_whitespace().map(|k| k.parse().unwrap());
        (
            it.next().unwrap(),
            it.next().unwrap(),
            )
    };

    let e = d - b;

    let (g, x, y) = extended_euclid(a, c);

    let ans = if e % g != 0 {
        -1
    } else {
        let x1 = x * e / g;
        let x2 = modulo(x1, c / g);

        let y1 = y * e / g;
        let y2 = modulo(-y1, a / g);

        max(b + x2 * a, d + y2 * c)
    };

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


fn gcd(mut x: usize, mut y: usize) -> usize {
    while y != 0 {
        let z = x%y;
        x = y;
        y = z;
    }
    x
}

fn lcm(x: usize, y: usize) -> usize {
    x * y / gcd(x, y)
}

fn main() {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let mut line = line.split_whitespace();
    let a = line.next().unwrap().parse::<usize>().unwrap();
    let b = line.next().unwrap().parse::<usize>().unwrap();
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let mut line = line.split_whitespace();
    let c = line.next().unwrap().parse::<usize>().unwrap();
    let d = line.next().unwrap().parse::<usize>().unwrap();

    let mut counter_one = 0;
    let mut counter_two = 0;
    let limit = lcm(a, c);
    loop {
        let (x, y) = (counter_one + b, counter_two + d);
        if x == y {
            println!("{}", x);
            return;
        } else if x < y {
            counter_one += a;
        } else {
            counter_two += c;
        }
        if counter_one > limit && counter_two > limit {
            println!("-1");
            return;
        }
    }
}


use std::io::{Read, stdin};

fn main() {
    let mut buf = String::new();
    stdin().read_to_string(&mut buf).unwrap();
    let mut tok = buf.split_whitespace();
    let mut get = || tok.next().unwrap();
    macro_rules! get {
        ($t:ty) => (get().parse::<$t>().unwrap());
        () => (get!(usize));
    }

    let n = get!();
    let m = get!();
    let mut fs = vec![0; 101];
    for _ in 0..m {
        fs[get!()] += 1;
    }
    let fs: Vec<_> = fs
        .into_iter()
        .filter(|v| *v > 0)
        .collect();

    let mut ans = 0;
    for i in 1..101 {
        let mut c = 0;
        for &f in fs.iter() {
            c += f / i;
        }
        if c >= n {
            ans = i;
        }
    }
    println!("{}", ans);
}


use std::io;

macro_rules! except {
    ($result: expr) => {
        match $result {
            Err(e) => panic!("{}", e),
            Ok(m) => m,
        }
    };
    ($result: expr, $msg: expr) => {
        match $result {
            Err(e) => panic!("{}: {}", $msg, e),
            Ok(m) => m,
        }
    };
}

fn parse_line() -> Vec<u8> {
    let mut input = String::new();
    except!(io::stdin().read_line(&mut input));
    input.trim().split_whitespace()
       .map(|x| except!(x.parse::<u8>()))
       .collect()
}

const MAXN: u8 = 100;

fn main() {
    let n = parse_line()[0];
    let a = parse_line();
    let counts = a.iter().fold([0u8; 101], |mut v, &x| {v[x as usize] += 1; v});
    for i in 1..MAXN + 1 {
        if n > counts.iter().fold(0, |v, x| v + x / i) {
            println!("{}", i - 1);
            return
        }
    }
    println!("{}", MAXN);
}


use std::io;

macro_rules! unwrap {
    ($result: expr) => {
        match $result {
            Err(e) => panic!("{}", e),
            Ok(m) => m,
        }
    };
}

fn parse_line() -> Vec<u8> {
    let mut input = String::new();
    unwrap!(io::stdin().read_line(&mut input));
    input.trim().split_whitespace()
       .map(|x| unwrap!(x.parse::<u8>()))
       .collect()
}

const MAXN: u8 = 100;

fn main() {
    let n = parse_line()[0];
    let a = parse_line();
    let counts = a.iter().fold([0u8; MAXN as usize + 1], |mut v, &x| {v[x as usize] += 1; v});
    for i in 1..counts.len() as u8 / n + 2 {
        if n > counts.iter().fold(0, |v, x| v + x / i) {
            println!("{}", i - 1);
            return
        }
    }
    println!("{}", MAXN);
}


use std::io;

macro_rules! except {
    ($result: expr) => {
        match $result {
            Err(e) => panic!("{}", e),
            Ok(m) => m,
        }
    };
    ($result: expr, $msg: expr) => {
        match $result {
            Err(e) => panic!("{}: {}", $msg, e),
            Ok(m) => m,
        }
    };
}

fn parse_line() -> Vec<u8> {
    let mut input = String::new();
    except!(io::stdin().read_line(&mut input));
    input.trim().split_whitespace()
       .map(|x| except!(x.parse::<u8>()))
       .collect()
}

fn main() {
    let n = parse_line()[0] as usize;
    let a = parse_line();
    if n > a.len() {
        println!("0");
        return
    }
    let mut counts = a.iter().fold([0u8; 101], |mut v, &x| {v[x as usize] += 1; v});
    counts.sort_unstable_by(|x, y| y.cmp(x));
    let mut nums = vec![0u8; n];
    for _ in 0..n {
        let (index, _) = nums.iter().enumerate()
            .max_by_key(|&(i, v)| counts[i] / (v + 1)).unwrap();
        nums[index] += 1;
    }
    let (index, _) = nums.iter().enumerate().filter(|&(_, v)| *v != 0)
        .min_by_key(|&(i, v)| counts[i] / v).unwrap();
    println!("{}", counts[index] / nums[index]);
}


use std::io;

fn gcd(mut u: u64, mut v: u64) -> u64 {
    if u == 0 {
        return v;
    }
    if v == 0 {
        return u;
    }

    let mut shift = 0;
    let mut aux : [u64; 2] = [(u | v), 1];
    while aux[0] & aux[1] == 0 {
        shift += 1;
        aux[1] <<= 1;
    }
    u >>= shift;
    v >>= shift;

    while u & 1 == 0 {
        u >>= 1;
    }

    loop {
        while v & 1 == 0 {
            v >>= 1;
        }

        if u > v {
            aux[0] = v;
            v = u;
            u = aux[0];
        }
        v -= u;

        if v == 0 {
            break;
        }
    }
    u << shift
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("failed to read input");
    let mut input_iter = input.split_whitespace();
    let a = input_iter.next().unwrap().parse::<u64>().unwrap();
    let b = input_iter.next().unwrap().parse::<u64>().unwrap();

    let md = if a > b { a - b } else { b - a };
    let sqrt_md = (md as f64).sqrt() as u64 + 1;
    let mut lcm_min = 4 * a * b;
    let mut min_k = 0;
    let mut vec = Vec::new();
    for i in (1..=sqrt_md).filter(|x| md % x == 0) {
        vec.push(md / i);

        let mut k = a % i;
        if k != 0 {
            k = i - k;
        }

        let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));
        if lcm < lcm_min {
            lcm_min = lcm;
            min_k = k;
        }
    }
    if md != 0 {
        for i in vec {
            let mut k = a % i;
            if k != 0 {
                k = i - k;
            }

            let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));
            if lcm < lcm_min {
                lcm_min = lcm;
                min_k = k;
            }
        }
    }

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


fn is_sufficient(v: u64, n: u64, k: u64) -> bool {
    let summand_count = ((v as f64).log(k as f64).trunc() + 1_f64) as usize;
    // dbg!(summand_count);
    let sum: u64 = (0..summand_count).map(|x| v / k.checked_pow(x as u32).unwrap()).sum();
    // dbg!(sum);
    sum >= n
}

fn solve(n: u64, k: u64) -> u64 {
    let mut l: u64 = 1;
    let mut r: u64 = n + 1;
    while r - l > 2 {
        let m = l + (r - l) / 2;
        // dbg!(l, m, r);
        if is_sufficient(m, n, k) {
            // dbg!("YES");
            r = m + 1;
        } else {
            // dbg!("NO");
            l = m;
        }
    }
    // dbg!(is_sufficient(4, n, k));
    if is_sufficient(l, n, k) {l} else {l + 1}
}

fn main() {
    let (n, k) = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let mut n_k = buf.trim().split_whitespace().map(|x| x.parse::<u64>().unwrap());
        let n = n_k.next().unwrap();
        let k = n_k.next().unwrap();
        (n, k)
    };

    println!("{}", solve(n, k));
}


use std::io;

fn bs<F>(f: F, mut mi: i64, mut ma: i64) -> i64
where
    F: Fn(i64) -> bool,
{
    let mut mm = 0;
    while mi < ma {
        mm = (mi + ma) / 2;
        if f(mm) {
            mi = mm + 1;
        } else {
            ma = mm;
        }
    }
    if f(mm) {
        mm + 1
    } else {
        mm
    }
}

#[allow(dead_code)]
fn solve() -> Vec<String> {
    let mut input = "".split_ascii_whitespace();
    let mut read = || loop {
        if let Some(word) = input.next() {
            break word;
        }
        input = {
            let mut input = "".to_owned();
            io::stdin().read_line(&mut input).unwrap();
            if input.is_empty() {
                panic!("reached EOF");
            }
            Box::leak(input.into_boxed_str()).split_ascii_whitespace()
        };
    };
    macro_rules! read(($ty:ty) => (read().parse::<$ty>().unwrap()));

    let mut rr = vec!["".to_string(); 0];

    let t = 1;
    for _ in 0..t {
        let n = read!(i64);
        let k = read!(i64);

        let f = |i| {
            let mut u: i64 = 0;
            let mut kk = 1;
            while kk <= i {
                u += i / kk;
                kk *= k;
            }
            u < n
        };

        let r = bs(f, 0, n);
        rr.push(format!("{}", r));
    }

    rr
}

#[allow(dead_code)]
fn main() {
    let output = solve();
    println!("{}", output.join("\n"));
}


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

fn main() {
    let input = get_input()
        .trim()
        .split(" ")
        .map(|s| s.parse::<u64>().unwrap())
        .collect::<Vec<u64>>();

    let rows = input[0];
    let columns = input[1];

    if rows == 1 {
        println!("{}", columns - 1);
        return;
    }

    if columns == 1 {
        println!("{}", rows - 1);
        return;
    }

    println!("{}", rows * (columns - 1));
}


fn main() {
    let stdin = std::io::stdin();
    let mut input = std::io::BufReader::new(stdin);
    let a = read_vec_i64(&mut input);
    let solution = solve(a[0], a[1]);
    println!("{solution}");

}

fn solve(n: i64, m: i64,) -> i64 {
    if m == 1 {
        n - 1
    }
    else {
        n * (m - 1)
    }
}

#[allow(dead_code)]
fn read_i32(reader: &mut impl std::io::BufRead) -> i32 {
    let mut line = String::new();
    reader.read_line(&mut line).unwrap();
    line.trim().parse::<i32>().unwrap()
}

#[allow(dead_code)]
fn read_vec_i32(reader: &mut impl std::io::BufRead) -> Vec<i32> {
    let mut line = String::new();
    reader.read_line(&mut line).unwrap();
    line = line.trim().into();
    line.split(" ").map(|s| s.parse::<i32>().unwrap()).collect()
}

#[allow(dead_code)]
fn read_i64(reader: &mut impl std::io::BufRead) -> i64 {
    let mut line = String::new();
    reader.read_line(&mut line).unwrap();
    line.trim().parse::<i64>().unwrap()
}

#[allow(dead_code)]
fn read_vec_i64(reader: &mut impl std::io::BufRead) -> Vec<i64> {
    let mut line = String::new();
    reader.read_line(&mut line).unwrap();
    line = line.trim().into();
    line.split(" ").map(|s| s.parse::<i64>().unwrap()).collect()
}

#[allow(dead_code)]
fn read_string(reader: &mut impl std::io::BufRead) -> String {
    let mut line = String::new();
    reader.read_line(&mut line).unwrap();
    line.trim().into()
}

#[allow(dead_code)]
fn read_chars(reader: &mut impl std::io::BufRead) -> Vec<char> {
    let mut line = String::new();
    reader.read_line(&mut line).unwrap();
    line.trim().chars().collect()
}


fn main() {
    let mut input_line = String::new();
    std::io::stdin()
        .read_line(&mut input_line)
        .expect("Failed to read line");

    let mut parts = input_line.split_whitespace();
    let n: usize = parts.next().expect("Not enough input numbers")
           .parse().expect("Input is not a number");
    let m: usize = parts.next().expect("Not enough input numbers")
           .parse().expect("Input is not a number");

    if m == 1 {
        println!("{}", n - 1)
    } else {
        println!("{}", n * (m - 1));
    }
}


#![allow(unused_imports)]
use std::io::*;
use std::cmp::*;
use std::collections::*;

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

struct Scanner {
   buffer : std::collections::VecDeque<String>
}

impl Scanner {

   fn new() -> Scanner {
      Scanner {
         buffer: std::collections::VecDeque::new()
      }
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {

      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      let front = self.buffer.pop_front().unwrap();
      front.parse::<T>().ok().unwrap()
   }
}

fn main() {
   let mut s = Scanner::new();
   let input = s.next::<String>();
   let mut iter = input.chars();
   let column = iter.next().unwrap();
   let row = iter.next().unwrap();

   if column == 'a' || column == 'h' {
      if row == '1' || row == '8' {
         println!("3");
      } else {
         println!("5");
      }
   } else if row == '1' || row == '8' {
      if column == 'a' || column == 'h' {
         println!("3");
      } else {
         println!("5");
      }
   } else {
      println!("8");
   }
}


fn main() {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).expect("Error");
    let letter = line.chars().nth(0).expect("Error");
    let number = line.chars().nth(1).expect("Error");
    let array = [letter, number];

    fn boundary(a: char) -> bool {
        match a {
            'a' | 'h' | '1' | '8' => true,
            _ => false,
        }
    }
    let cnt = array.iter().map(|x| boundary(*x)).filter(|x| *x).count();

    let res = match cnt {
        0 => 8,
        1 => 5,
        2 => 3,
        _ => unreachable!(),
    };
    println!("{}", res);
}


use std::io;

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

    io::stdin().read_line(&mut guess)
        .expect("Failed to read whatever you enter");

    let first = guess.chars().nth(0).unwrap();
    let second = guess.chars().nth(1).unwrap();
    let mut allow = 8;
    let mut left_or_rigt_most = false;

    if first == 'a' || first == 'h' {
        left_or_rigt_most = true;
        allow -= 3;
    }

    if second == '1' || second == '8' {
        if left_or_rigt_most {
            allow -= 2;
        } else {
            allow -= 3;
        }
    }

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


// Try Codeforces
// author: Leonardone @ NEETSDKASU

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

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

    fn solve(n: i64, k: i64) -> bool {
        if k == 1 {
            return true;
        }
        if k >= n {
            return n == 1 && (k <= 2);
        }
        let mut k = k;
        while k > 0 {
            if n % k != k - 1 {
                return false;
            }
            k -= 1
        }
        true
    }

    if solve(n, k) {
        println!("Yes");
    } else {
        println!("No");
    }

    for a in 1..31 {
        for b in 1..31 {
            let mut ok = true;
            let mut f = vec![false; b+1];
            for i in 1..b+1 {
                let p = a % i;
                if f[p] {
                    ok = false;
                    break;
                }
                f[p] = true;
            }
            if ok != solve(a as i64, b as i64) {
                println!("{} {} {}", a, b, ok);
            }
        }
    }
}


/*
 *
 * Author : fcbruce <fcbruce8964@gmail.com>
 *
 * Time : Sat 10 Feb 2018 20:02:28
 *
 */

fn main() {

  let mut buffer = String::new();
  std::io::stdin().read_line(&mut buffer).unwrap();
  let mut numbers = buffer.split_whitespace();
  let n: u64 = numbers.next().unwrap().parse::<u64>().unwrap();
  let k: u64 = numbers.next().unwrap().parse::<u64>().unwrap();

  let max: usize = 100000;

  let mut remainders = vec![false; max];

  let mut min = k + 1;

  for i in 1..std::cmp::min::<u64>(max as u64, k + 1) {
    let r: usize = (n % i) as usize;
    if remainders[r] {
      min = i;
      break;
    }
    remainders[r] = true;
  }

  if k == 1 || k < min {
    println!("Yes");
  } else {
    println!("No");
  }

}


fn main() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("input: read line failed");
    let number = input.trim().parse::<i32>().expect("number: parse to usize failed");

    let vec = vec![
        hp_judge(0, number),
        hp_judge(1, number),
        hp_judge(2, number),
    ];

    let outcome = great_hp(vec);

    println!("{} {}", outcome.0, outcome.1);

}

fn great_hp(hp_vec: Vec<(i32, i32)>) -> (i32, String) {
    let mut best_hp = (i32::default(), i32::default());

    for item in hp_vec.iter() {
        if item.1 > best_hp.1 {
            best_hp = *item;
        }
    }

    convert(best_hp)
}

fn hp_judge(offset: i32, number: i32) -> (i32, i32) {
    ( offset, grade_estimation(number + offset) )
}

fn grade_estimation(hp: i32) -> i32 {
    let reminder = hp % 4;

    match reminder {
        0 => { 0 },
        1 => { 3 },
        2 => { 1 },
        3 => { 2 },
        _ => { -1 },

    }
}

fn convert(hp: (i32, i32)) -> (i32 ,String) {
    match hp.1 {
        0 => { (hp.0, String::from("D")) },
        3 => { (hp.0, String::from("A")) },
        1 => { (hp.0, String::from("C")) },
        2 => { (hp.0, String::from("B")) },
        _ => { (hp.0, String::from("Err")) },
    }
}


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

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

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

fn get_class(x: usize) -> usize {
    let classes = [0usize, 2, 3, 1];
    return classes.iter().position(|&v| v == (x % 4)).unwrap();
}

fn _main() {
    let mut scan = Scan::new();
    let x: usize = scan.next();
    let mut maxclass = get_class(x);
    let mut maxb = 0;
    for &step in [1usize, 2].iter() {
        let current_class = get_class(x + step);
        if current_class > maxclass {
            maxclass = current_class;
            maxb = step;
        }
    }
    println!("{} {}", maxb, ['D', 'C', 'B', 'A'][maxclass]);
}

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


use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

pub fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let x = i.read::<u32>();

    let (a, b) = solve(x);
    writeln!(o, "{} {}", a, b).unwrap();
}
fn solve(x: u32) -> (u32, char) {
    fn to_category(x: u32) -> char {
        match x % 4 {
            1 => 'A',
            3 => 'B',
            2 => 'C',
            0 => 'D',
            _ => unreachable!(),
        }
    }
    [0, 1, 2]
        .iter()
        .map(|&a| (a, to_category(x + a)))
        .min_by_key(|&(_a, c)| c)
        .unwrap()
}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            let mut consume = 0;
            loop {
                self.r.consume(consume);
                let b = self.r.fill_buf().unwrap();
                assert!(b.len() != 0);
                if let Some(p) = b.iter().position(|&x| x.is_ascii_whitespace()) {
                    self.b.extend_from_slice(&b[..p]);
                    consume = p + 1;
                    break;
                }
                self.b.extend_from_slice(b);
                consume = b.len();
            }
            self.r.consume(consume);
            consume_ws(&mut self.r);
            &self.b
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            let end = self
                .b
                .iter()
                .rposition(|x| !x.is_ascii_whitespace())
                .map(|idx| idx + 1)
                .unwrap_or(0);
            &self.b[..end]
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpIn>(&mut self) -> T {
            T::read_from(self)
        }

        pub fn read_vec<T: CpIn>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
        pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {
            CpIter {
                r: self,
                n: n,
                _pd: Default::default(),
            }
        }
    }
    pub struct CpIter<'a, R: BufRead + 'a, T> {
        r: &'a mut CpReader<R>,
        n: usize,
        _pd: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            if self.n == 0 {
                None
            } else {
                self.n -= 1;
                Some(self.r.read())
            }
        }
    }

    pub trait CpIn {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpIn for u64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpIn for i64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }
    impl CpIn for char {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            let b = r.r.fill_buf().unwrap()[0] as char;
            r.r.consume(1);
            let s = r.r.fill_buf().unwrap()[0];
            assert!(s == b' ' || s == b'\n');
            r.r.consume(1);
            b
        }
    }

    macro_rules! cpin_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpIn),*> CpIn for ($($t),*) {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::read_from(r)),*)
                }
            }
        };
    }

    macro_rules! cpin_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpIn for $t_self {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::read_from(r) as $t_self
                }
            }
        };
    }
    macro_rules! cpin_parse {
        ($t:ty) => {
            impl CpIn for $t {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }
    cpin_cast!(usize, u64);
    cpin_cast!(u32, u64);
    cpin_cast!(u16, u64);
    cpin_cast!(i32, i64);
    cpin_cast!(i16, i64);
    cpin_cast!(i8, i64);

    cpin_parse!(f64);

    cpin_tuple!(T1, T2);
    cpin_tuple!(T1, T2, T3);
    cpin_tuple!(T1, T2, T3, T4);
    cpin_tuple!(T1, T2, T3, T4, T5);

    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let mut idx = 0;
            let buf_len;
            {
                let buf = r.fill_buf().unwrap();
                buf_len = buf.len();
                assert!(buf_len != 0);
                while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {
                    value = value * 10 + (buf[idx] - b'0') as u64;
                    idx += 1;
                }
            }
            if idx < buf_len {
                r.consume(idx);
                consume_ws(r);
                return value;
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let (consume, sign) = match r.fill_buf().unwrap()[0] {
            b'+' => (true, 1),
            b'-' => (true, -1),
            _ => (false, 1),
        };
        if consume {
            r.consume(1);
        }
        read_u64_fast(r) as i64 * sign
    }
    fn consume_ws<R: BufRead>(r: &mut R) {
        let mut c = 0;
        loop {
            r.consume(c);
            let b = r.fill_buf().unwrap();
            if b.len() == 0 {
                return;
            }
            if let Some(p) = b.iter().position(|&x| !x.is_ascii_whitespace()) {
                c = p;
                break;
            }
            c = b.len();
        }
        r.consume(c);
    }

}


// Template adapted from submissions by https://codeforces.com/profile/EbTech

#[allow(unused_imports)]
use std::io::*;

#[derive(Default)]
struct Scanner(Vec<String>);
impl Scanner {
    fn read<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.0.pop() {
                return token.parse().ok().unwrap();
            }
            let mut input = String::new();
            stdin().read_line(&mut input).unwrap();
            self.0 = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut cin = Scanner::default();
    let cout = &mut BufWriter::new(stdout());

    let x: u8 = cin.read();
    let (a, b) = match x % 4 {
        1 => (0, 'A'),
        3 => (2, 'A'),
        2 => (1, 'B'),
        0 => (1, 'A'),
        _ => unreachable!(),
    };

    writeln!(cout, "{} {}", a, b).unwrap();
}


use std::collections::HashMap;

fn read_string() -> String {
    let mut string: String = String::new();

    std::io::stdin().read_line(&mut string)
        .ok()
        .expect("Error read line!");
    return string;
}

fn main() {

    let hp : i32 = read_string().trim().parse().ok().expect("not int");

    let mut category : HashMap<i32, &str> = HashMap::new();
    category.insert(1, "0 A");
    category.insert(3, "2 A");
    category.insert(2, "1 B");
    category.insert(0, "1 A");
    println!("{}", category[&(hp % 4)]);
}


#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Score{
    grade: String,
    score: i32
}

fn calculate_grade(grade: i32) -> String{
    let mut words : String;
    match grade {
        1 => words = String::from("A"),
        2 => words = String::from("C"),
        3 => words = String::from("B"),
        _ => words = String::from("D")
    }
    words
}

fn main() {
    let mut t: String = String::new();
    std::io::stdin().read_line(&mut t).expect("input");
    let counter:Vec<i32> = t.trim()
        .split_whitespace()
        .map(|x| x.parse::<i32>().expect("Not an Integer!"))
        .collect();

    let mut list_of_score : Vec<Score> = Vec::new();
    for i in 0..3{
        list_of_score.push( Score {
            score: i ,
            grade: calculate_grade((counter[0] + i) % 4)
        })
    }
    list_of_score.sort();
    println!("{} {}", list_of_score[0].score, list_of_score[0].grade);
}


//spnauti-rust
use std::io::*;
use std::str::*;
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::*;
#[allow(unused_imports)] use std::collections::*;

#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).unwrap();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn vi(&mut self, n: usize) -> Vec<i32> {
        self.vp::<i32>(n)
    }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

#[allow(dead_code)]
fn build_counting_hashmap<K: Eq + std::hash::Hash, T>(i: T) -> HashMap<K,usize>
    where T: Iterator<Item = K> {
    let mut m = HashMap::new();
    for k in i {
        let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };
        m.insert(k, n);
    }
    m
}

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

    let n = input.u();
    let mut a = vec![0; 3];
    for i in 0..n {
        a[i % 3] += input.i();
    }
    let max = a.iter().max().unwrap();
    for (x,y) in vec!["chest","biceps","back"].into_iter().zip(a.iter()) {
        if max == y {
            println!("{}", x);
        }
    }
}


fn input_count() -> [u8; 3] {
    let mut buf = String::new();
    let mut body = [0; 3];
    std::io::stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|elem| elem.parse::<u8>().unwrap())
        .zip(0..)
        .for_each(|(a_i, i)| body[i % 3] += a_i);
    body
}

fn main() {
    {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
    }
    println!(
        "{}",
        input_count()
            .iter()
            .zip(["chest", "biceps", "back"].iter())
            .max()
            .unwrap()
            .1
    );
}


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

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

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

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    let mut cnt = [0usize; 3];
    let ex_msg = ["chest", "biceps", "back"];
    let mut maxa = 0usize;
    let mut maxi = 0usize;
    for i in 0..n {
        let a: usize = scan.next();
        let exi = i % 3;
        cnt[exi] += a;
        if cnt[exi] > maxa {
            maxa = cnt[exi];
            maxi = exi;
        }
    }
    println!("{}", ex_msg[maxi]);
}

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


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

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

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

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

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

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

fn main() {
    let mut field: Vec<Vec<char>> = (0..11).map(|_| util::line().chars().collect()).collect();
    let (mut y, mut x) = get!(usize, usize);

    y -= 1;
    x -= 1;

    let ry = y - 3 * (y / 3);
    let rx = x - 3 * (x / 3);

    let sy = 4 * ry;
    let sx = 4 * rx;

    if (sy..sy + 3).all(|y1| (sx..sx + 3).all(|x1| field[y1][x1] != '.')) {
        for v in field.iter_mut() {
            for c in v.iter_mut() {
                if *c == '.' {
                    *c = '!';
                }
            }
        }
    } else {
        for y1 in sy..sy + 3 {
            for x1 in sx..sx + 3 {
                if field[y1][x1] == '.' {
                    field[y1][x1] = '!';
                }
            }
        }
    }

    for line in &field {
        println!(
            "{}",
            line.iter()
                .map(|c| c.to_string())
                .collect::<Vec<_>>()
                .join("")
        );
    }
}


// Try Codeforces
// author: Leonardone @ NEETSDKASU

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

    let mut field = vec![vec![]; 9];
    for i in 0..9 {
        for _ in 0..3 {
            field[i].push(get().as_bytes());
        }
    }
    let y = (get!(usize) - 1) % 3;
    let x = (get!(usize) - 1) % 3;

    let mut c = 0;
    for i in 0..3 {
        for &ch in &field[y*3+i][x][..] {
            if ch == b'.' {
                c += 1;
            }
        }
    }
    if c == 0 {
        for i in 0..9 {
            for j in 0..3 {
                if j > 0 { print!(" "); }
                for k in 0..3 {
                    let ch = field[i][j][k];
                    if ch == b'.' {
                        print!("!");
                    } else {
                        print!("{}", ch as char);
                    }
                }
            }
            println!();
            if i % 3 == 2 { println!(); }
        }
        return;
    }
    for i in 0..9 {
        for j in 0..3 {
            if j > 0 { print!(" "); }
            for k in 0..3 {
                let ch = field[i][j][k];
                if ch == b'.' && j == x && i / 3 == y {
                    print!("!");
                } else {
                    print!("{}", ch as char);
                }
            }
        }
        println!();
        if i % 3 == 2 { println!(); }
    }
}


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

    let p = input.bytes().position(|b| b'0' <= b && b <= b'9').unwrap();

    let grid: Vec<_> = input.as_bytes()[0..p].iter().filter_map(|&b| match b {
        b'.' => Some(Cell::Empty),
        b'x' => Some(Cell::Chip1),
        b'o' => Some(Cell::Chip2),
        _ => None,
    }).collect();

    let check = |x: usize, y: usize, grid: &Vec<Cell>| {
        let x_off = 27 * x;
        let y_off = 3 * y;
        let mut it = grid[x_off + y_off..].iter().take(3)
            .chain(grid[x_off + y_off + 9..].iter().take(3))
            .chain(grid[x_off + y_off + 18..].iter().take(3));

        !it.all(|cell| match *cell {
            Cell::Empty => false,
            _ => true,
        })
    };

    let mut it = input[p..].split_whitespace();
    let x: usize = it.next().unwrap().parse::<usize>().unwrap() - 1;
    let y: usize = it.next().unwrap().parse::<usize>().unwrap() - 1;

    let bx = x % 3;
    let by = y % 3;

    let ans: Vec<_> = if !check(bx, by, &grid) {
        grid.into_iter().map(|cell| match cell {
            Cell::Empty => Cell::Possible,
            _ => cell,
        }).collect()
    } else {
        grid.into_iter().enumerate().map(|(i, cell)| {
            let x = i / 9;
            let y = i % 9;
            match cell {
                Cell::Empty if x / 3 == bx && y / 3 == by => Cell::Possible,
                _ => cell,
            }
        }).collect()
    };

    let mut ans_str = Vec::with_capacity(2 * p);

    for (i, cell) in ans.into_iter().enumerate() {
        let next = match cell {
            Cell::Empty => b'.',
            Cell::Chip1 => b'x',
            Cell::Chip2 => b'o',
            Cell::Possible => b'!',
        };

        ans_str.push(next);

        if i % 27 == 26 {
            ans_str.push(b'\n');
        }
        if i % 9 == 8 {
            ans_str.push(b'\n');
        } else if i % 3 == 2 {
            ans_str.push(b' ');
        }
    }

    let ans = String::from_utf8(ans_str).unwrap();

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

#[derive(Debug)]
enum Cell {
    Empty,
    Chip1,
    Chip2,
    Possible,
}


mod util {
    use std;
    pub fn read_line() -> String {
        let mut buffer = String::new();
        std::io::stdin().read_line(&mut buffer).unwrap();
        String::from(buffer.trim_right())
    }
    #[allow(dead_code)]
    pub fn read_ascii() -> Vec<u8> {
        let line = read_line();
        debug_assert!(line.is_ascii());
        line.bytes().collect()
    }
    #[allow(dead_code)]
    pub fn read1() -> i64 {
        read_line().parse::<i64>().unwrap()
    }
    #[allow(dead_code)]
    fn read_nums<T: std::str::FromStr>() -> Vec<T>
        where <T as std::str::FromStr>::Err : std::fmt::Debug {
        read_line().split(' ').map(|x| x.parse::<T>().unwrap()).collect()
    }
    #[allow(dead_code)]
    pub fn read_ints() -> Vec<i64> {
        read_nums::<i64>()
    }
    #[allow(dead_code)]
    pub fn read_floats() -> Vec<f64> {
        read_nums::<f64>()
    }
    #[allow(dead_code)]
    pub fn read2() -> (i64, i64) {
        let nums = read_ints();
        (nums[0], nums[1])
    }
    #[allow(dead_code)]
    pub fn read3() -> (i64, i64, i64) {
        let nums = read_ints();
        (nums[0], nums[1], nums[2])
    }
    #[allow(dead_code)]
    pub fn read4() -> (i64, i64, i64, i64) {
        let nums = read_ints();
        (nums[0], nums[1], nums[2], nums[3])
    }
} // mod util
use util::*;

type Prime = i64;
type Power = usize;
type PrimePower = (Prime, Power);
type Factorization = Vec<PrimePower>;

fn primes_below(maxn: usize) -> Vec<Prime> {
    if maxn <= 2 {
        return vec![];
    }
    let mut is_prime: Vec<bool> = vec![true; maxn];
    is_prime[0] = false;
    is_prime[1] = false;
    let mut iterator: i64 = 2;
    while iterator * iterator < maxn as i64 {
        if is_prime[iterator as usize] {
            let mut destroyer: i64 = iterator * iterator;
            while destroyer < maxn as i64 {
                is_prime[destroyer as usize] = false;
                destroyer += iterator;
            }
        }
        iterator += 1;
    }
    is_prime.iter().enumerate().filter(|pair| *pair.1)
        .map(|pair| pair.0 as Prime).collect()
}

fn naive_factorization(mut number: i64, primes_till_sqrt: &Vec<Prime>) -> Factorization {
    let mut prime_iter: usize = 0;
    let mut prime: Prime;
    let mut answer: Factorization = vec![];
    while number != 1 {
        if prime_iter >= primes_till_sqrt.len() {
            answer.push((number, 1));
            return answer;
        }
        prime = primes_till_sqrt[prime_iter];
        if number % prime == 0 {
            let mut power: Power = 0;
            while number % prime == 0 {
                power += 1;
                number /= prime;
            }
            answer.push((prime, power));
        }
        prime_iter += 1;
    }
    answer
}

fn main() {
    let b = read1();
    let v = primes_below(100000);
    let mut ans = 1;
    for (_p, val) in naive_factorization(b, &v) {
        ans *= (val + 1);
    }
    println!("{}", ans);
}


use std::io::stdin;
fn main() {
    let mut text = String::new();
    stdin().read_line(&mut text).unwrap();
    let text: Vec<&str> = text.trim().split_whitespace().collect();
    let mut value = 0;

    let mut val: Vec<String> = vec![];
    let a = text[0].chars().collect::<Vec<char>>();
    let b = text[1].chars().collect::<Vec<char>>();
    let mut text1 = String::new();
    for x in &a {
        text1.push(*x);
        let mut text2 = String::new();

        for y in &b {
            text2.push(*y);
            val.push(text1.clone() + &text2[..]);
        }
    }
    val.sort();
    println!("{}", val[0]);
}


use std::io;

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

    io::stdin().read_line(&mut input).unwrap();

    let parts: Vec<&str> = input.trim().split(' ').collect();
    let mut logins: Vec<String> = vec![];

    for i in 1..(parts[0].len()+1) {
        for j in 1..(parts[1].len()+1) {
            let mut login = String::new();
            login.push_str(&parts[0][0..i]);
            login.push_str(&parts[1][0..j]);
            logins.push(login);
        }
    }

    logins.sort();

    println!("{}", logins[0]);
}


use std::io::stdin;
fn main() {
    let mut text = String::new();
    stdin().read_line(&mut text).unwrap();
    let text: Vec<&str> = text.trim().split_whitespace().collect();

    let mut val: Vec<String> = vec![];
    let a = text[0].chars().collect::<Vec<char>>();
    let b = text[1].chars().collect::<Vec<char>>();
    let mut text1 = String::new();
    if a.len() > 1 {
        for x in &a[1..] {
            if x < &b[0] {
                text1.push(*x);
            } else {
                break;
            }
        }
    }
    val.sort();
    println!("{}{}{}", a[0], text1, b[0]);
}


pub use __cargo_equip::prelude::*;

fn main() {
    cf_utils::cf_prelude!();

    const MODULUS: u64 = 1_000_000_007;

    for _ in 0..read!() {
        let n = read!(u64);
        let k = read!(u64);

        let upper = modexp(2, n - 1, MODULUS) - 1;

        let mut result = 1;

        for bit in 0..k {
            if n % 2 == 1 {
                result *= upper + 2;
                result %= MODULUS;
            } else {
                result *= upper;
                result %= MODULUS;
                result += modexp(2, n * bit, MODULUS);
                result %= MODULUS;
            }
        }

        outln!("{}", result % MODULUS);
    }
}

fn modexp(mut base: u64, mut exp: u64, modulus: u64) -> u64 {
    let mut result = 1;

    while exp > 0 {
        if exp & 1 != 0 {
            result *= base;
            result %= modulus;
        }

        exp >>= 1;
        base *= base;
        base %= modulus;
    }

    result
}

// The following code was expanded by `cargo-equip`.

///  # Bundled libraries
///
///  - `cf_utils 0.1.0 (git+https://github.com/jakobrs/cf_utils#efb13574168dc8cf0a033c3cc262f744480ed4b2)` licensed under `MIT` as `crate::__cargo_equip::crates::cf_utils`
///
///  # License and Copyright Notices
///
///  - `cf_utils 0.1.0 (git+https://github.com/jakobrs/cf_utils#efb13574168dc8cf0a033c3cc262f744480ed4b2)`
///
///      ```text
///      MIT License
///
///      Copyright (c) 2022 jakobrs
///
///      Permission is hereby granted, free of charge, to any person obtaining a copy
///      of this software and associated documentation files (the "Software"), to deal
///      in the Software without restriction, including without limitation the rights
///      to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
///      copies of the Software, and to permit persons to whom the Software is
///      furnished to do so, subject to the following conditions:
///
///      The above copyright notice and this permission notice shall be included in all
///      copies or substantial portions of the Software.
///
///      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
///      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
///      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
///      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
///      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
///      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
///      SOFTWARE.
///      ```
#[allow(unused)]
mod __cargo_equip {
    pub(crate) mod crates {
        pub mod cf_utils {
            pub use crate::__cargo_equip::macros::cf_utils::*;
            #[macro_export]
            macro_rules! /*_build_rest*/__cargo_equip_macro_def_cf_utils__build_rest {
                ($n:expr; $words:ident; $($accum:tt)*) => {
                    $words
                        .by_ref()
                        .take($n)
                        $($accum)*
                        .collect::<Vec<_>>()
                }
            }
            macro_rules!_build_rest{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__build_rest!{$($tt)*})}

            #[macro_export]
            macro_rules! /*_parse_rest*/__cargo_equip_macro_def_cf_utils__parse_rest {
                (decr; $($rest:tt)*) => {
                    $crate::__cargo_equip::crates::cf_utils::_build_rest!($($rest)* .map(|x| x - 1))
                };
                (decr, $($rest:tt)*) => {
                    $crate::__cargo_equip::crates::cf_utils::_parse_rest!($($rest)* .map(|x| x - 1))
                };
                ($filter:expr; $($rest:tt)*) => {
                    $crate::__cargo_equip::crates::cf_utils::_build_rest!($($rest)* .map($filter))
                };
                ($filter:expr, $($rest:tt)*) => {
                    $crate::__cargo_equip::crates::cf_utils::_parse_rest!($($rest)* .map($filter))
                }
            }
            macro_rules!_parse_rest{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__parse_rest!{$($tt)*})}

            #[macro_export]
            macro_rules! /*_define_read*/__cargo_equip_macro_def_cf_utils__define_read {
                ($words:ident, $dollar:tt) => {
                    #[allow(unused_macros)]
                    macro_rules! read {
                        () => {
                            $words.next().unwrap().parse().unwrap()
                        };
                        (raw) => {
                            $words.next().unwrap()
                        };
                        ($t:ty) => {
                            $words.next().unwrap().parse::<$t>().unwrap()
                        };
                        ($t:ty; $n:expr) => {
                            $crate::__cargo_equip::crates::cf_utils::_build_rest!($n; $words; .map(|s| s.parse::<$t>().unwrap()))
                        };
                        ($t:ty, $dollar ($dollar rest:tt)*) => {
                            $crate::__cargo_equip::crates::cf_utils::_parse_rest!($dollar ($dollar rest)*; $words; .map(|s| s.parse::<$t>().unwrap()))
                        }
                    }
                };
            }
            macro_rules!_define_read{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__define_read!{$($tt)*})}

            #[macro_export]
            macro_rules! /*_define_out*/__cargo_equip_macro_def_cf_utils__define_out {
                ($stdout:ident, $dollar:tt) => {
                    #[allow(unused_macros)]
                    macro_rules! out {
                        ($dollar ($dollar arg:tt)*) => {{
                            ::std::io::Write::write_fmt(&mut $stdout, format_args!($dollar ($dollar arg)*)).unwrap();
                        }};
                    }

                    #[allow(unused_macros)]
                    macro_rules! outln {
                        () => {{
                            ::std::io::Write::write_all(&mut $stdout, b"\n").unwrap();
                        }};
                        ($dollar ($dollar arg:tt)*) => {{
                            ::std::io::Write::write_fmt(&mut $stdout, format_args!($dollar ($dollar arg)*)).unwrap();
                            outln!();
                        }};
                    }
                }
            }
            macro_rules!_define_out{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__define_out!{$($tt)*})}

            #[macro_export]
            macro_rules! /*_cf_prelude*/__cargo_equip_macro_def_cf_utils__cf_prelude {
                () => {
                    let mut input = String::new();
                    std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).unwrap();
                    let mut words = input.split_whitespace();

                    let out = ::std::io::stdout();
                    let mut out = ::std::io::BufWriter::new(out.lock());

                    $crate::__cargo_equip::crates::cf_utils::define_read!(words, $);

                    $crate::__cargo_equip::crates::cf_utils::define_out!(out, $);
                };
            }
            macro_rules!_cf_prelude{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__cf_prelude!{$($tt)*})}

            pub use crate::__cargo_equip::crates::cf_utils::{
                _cf_prelude as cf_prelude, _define_out as define_out, _define_read as define_read,
            };
        }
    }

    pub(crate) mod macros {
        pub mod cf_utils {
            pub use crate::{
                __cargo_equip_macro_def_cf_utils__build_rest as _build_rest,
                __cargo_equip_macro_def_cf_utils__cf_prelude as _cf_prelude,
                __cargo_equip_macro_def_cf_utils__define_out as _define_out,
                __cargo_equip_macro_def_cf_utils__define_read as _define_read,
                __cargo_equip_macro_def_cf_utils__parse_rest as _parse_rest,
            };
        }
    }

    pub(crate) mod prelude {
        pub use crate::__cargo_equip::crates::*;
    }

    mod preludes {
        pub mod cf_utils {}
    }
}


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 %= MODULO as i64;
            answer += MODULO as i64;
            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()),
    }
}


//spnauti-rusT {{{
#[allow(unused_imports)]use std::{io::*,collections::*,fmt::Debug,str::{self,*},cmp::*,ops::{self,*},iter::{self,*}};
macro_rules!rp{{[$c:expr]$($s:tt)+}=>(for _ in 0..$c{$($s)+})}
macro_rules!l{
	($($v:ident),+:$t:ty=$e:expr)=>{$(let$v:$t=$e;)+};(mut $($v:ident),+ =$e:expr)=>{$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr)=>{$(let mut$v:$t=$e;)+};($($v:ident),+ =$e:expr)=>{$(let$v=$e;)+};}
macro_rules!v{
	($(:$t:ty)?=$e:expr)=>{$e$(as$t)?};([$d:expr]$(:$t:ty)?)=>{Vec::$(<$t>::)?with_capacity($d)};
	([]$(:$t:ty)?)=>{Vec::$(<$t>::)?new()};([$d:expr]$($s:tt)+)=>{vec![v!($($s)+);$d]};}
fn rio()->(Reader,BufWriter<Stdout>){(Reader::new(),BufWriter::new(stdout()))}
struct Reader{buf:Vec<u8>,pos:usize,x:*mut Stdin,q:StdinLock<'static>}//'
#[allow(dead_code)]impl Reader{
	fn new()->Self{let x=Box::into_raw(Box::new(stdin()));let q=unsafe{&*x}.lock();Self{x,q,buf:v!([]),pos:0}}
	fn next_line(&mut self)->bool{self.buf.clear();self.pos=0;self.q.read_until(b'\n',&mut self.buf).unwrap_or(0)>0}
	fn byte(&mut self)->Option<u8>{
		if self.pos==self.buf.len(){if!self.next_line(){return None;}}self.pos+=1;Some(self.buf[self.pos-1])}
	fn vb(&mut self)->Vec<u8>{let mut s=v!([10]);let mut f=false;while let Some(c)=self.byte(){
		if!c.is_ascii_whitespace(){s.push(c);f=true;}else if f{break;}}s}
	fn p<T:FromStr>(&mut self)->T where T::Err:Debug{let w=self.vb();str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()}
	fn u(&mut self) ->  usize { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
}impl Drop for Reader{fn drop(&mut self){unsafe{Box::from_raw(self.x)};}}
//----------}}}

// Field (mod prime) {{{
mod field {
	use std::ops::*;
	#[allow(dead_code)] pub const Z0: Field = Field(0);
	#[allow(dead_code)] pub const Z1: Field = Field(1);
	const P5: i32 = 1_000_000_007;
	const P6: i64 = P5 as i64;
	#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(i32);
	#[allow(dead_code)] impl Field {
		pub fn new<T: Into<i64>>(a: T) -> Self { Self(Self::cv(a)) }
		pub unsafe fn new_unchecked(a: i32) -> Self { Self(a) }
		fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }
		fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }
		fn cv<T: Into<i64>>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }
		pub fn inv(self) -> Self { self.pow(P5-2) }
		pub fn pow<T: Into<i64>>(self, b: T) -> Self {
			let b = b.into(); if b == 0 { Self(1) } else {
				let mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res
			}
		}
	}
	impl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}
	impl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}
	impl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}
	impl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}
	impl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}
	impl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }
	impl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }
	impl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }
	impl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }
	use std::fmt::{Display, Formatter, Result};
	impl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.0) } }
}
#[allow(unused_imports)] use field::{Field, Field as Z, Z0, Z1};
//}}}

fn main() {
	let (mut rin,mut rout) = rio();
	let z2 = Z::new(2);

	rp!{[rin.u()]
		let n = rin.l();
		let k = rin.u();
		let (c10,c) = if n % 2 == 0 {
			(Z1, z2.pow(n-1) - Z1)
		} else {
			(Z0, z2.pow(n-1) + Z1)
		};
		l!(mut x,p = Z1);
		let p2 = z2.pow(n);
		rp!{[k]
			x = c10 * p + c * x;
			p *= p2;
		}
		writeln!(rout, "{}", x).unwrap();
	}
}


#![allow(dead_code,unused_imports)]
#[rustfmt::skip] mod prefix_sum {use std::fmt::{self, Debug, Formatter};use std::ops::Add;#[derive(Clone)] pub struct PrefixOp<T, I, F> where I: Iterator<Item = T>, F: Fn(T, T) -> T, { iter: I, acc: Option<T>, f: F, }  impl<T, I, F> Iterator for PrefixOp<T, I, F> where I: Iterator<Item = T>, F: Fn(T, T) -> T, T: Clone, { type Item = T;fn next(&mut self) -> Option<Self::Item> { let next = self.iter.next();if let Some(next) = next { if let Some(acc) = self.acc.take() { self.acc = Some((self.f)(acc, next));} else { self.acc = Some(next);} Some(self.acc.clone().unwrap()) } else { None } } }  impl<T, I, F> Debug for PrefixOp<T, I, F> where I: Iterator<Item = T> + Debug, F: Fn(T, T) -> T, T: Debug, { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct("PrefixOp") .field("acc", &self.acc) .field("iter", &self.iter) .finish() } }  pub trait CreatePrefixOps<T, F>: Iterator<Item = T> + Sized where F: Fn(T, T) -> T, { fn prefix_ops(self, op: F) -> PrefixOp<Self::Item, Self, F>;}  impl<T, F, I> CreatePrefixOps<T, F> for I where I: Iterator<Item = T>, F: Fn(T, T) -> T, { fn prefix_ops(self, op: F) -> PrefixOp<Self::Item, Self, F> { PrefixOp { iter: self, acc: None, f: op, } } }  macro_rules! prefix_op_specialisation { ($trait_name:ident, $fn_name:ident, $fn:expr, $($bound_token:tt)+) => { pub trait $trait_name<T>: Iterator<Item = T> + Sized where $($bound_token)+ { fn $fn_name(self) -> PrefixOp<Self::Item, Self, fn(T, T) -> T>;}  impl<T, I> $trait_name<T> for I where I: Iterator<Item = T>, $($bound_token)+ { fn $fn_name(self) -> PrefixOp<Self::Item, Self, fn(T, T) -> T> { PrefixOp { iter: self, acc: None, f: $fn, } } } };}  prefix_op_specialisation!(CreatePrefixSums, prefix_sums, T::add, T: Add<Output = T>);prefix_op_specialisation!(CreatePrefixMax, prefix_max, T::max, T: Ord);prefix_op_specialisation!(CreatePrefixMin, prefix_min, T::min, T: Ord);}
#[rustfmt::skip] mod scanner {use std::io::{stdin, BufReader, Bytes, Error as IoError, Read, Stdin};use std::str::{self, FromStr, Utf8Error};#[derive(Debug)] pub struct Scanner<R: Read> { bytes: Bytes<BufReader<R>>, buf: Vec<u8>, }  #[derive(Debug)] pub enum ScanError<T: FromStr> { Io(IoError), Parse(T::Err, String), NonUtf8(Utf8Error, Vec<u8>), }  impl Scanner<Stdin> { pub fn stdin() -> Self { Self::new(stdin()) } }  impl<R: Read> Scanner<R> { pub fn new(reader: R) -> Self { Self { bytes: BufReader::new(reader).bytes(), buf: Vec::new(), } }  #[allow(clippy::should_implement_trait)] pub fn next<T: FromStr>(&mut self) -> Result<T, ScanError<T>> { assert!(self.buf.is_empty());for b in &mut self.bytes { let b = b.map_err(ScanError::Io)?;if b.is_ascii_whitespace() {  if self.buf.is_empty() { continue;} else { break;} } else { self.buf.push(b);} }   match str::from_utf8(&self.buf) { Err(err) => Err(ScanError::NonUtf8(err, std::mem::take(&mut self.buf))), Ok(s) => { let ret = s.parse().map_err(|err| ScanError::Parse(err, s.to_owned()));self.buf.clear();ret } } } }  #[macro_export] macro_rules! scan { ($scanner:expr) => { $scanner.next().expect("failed to read token") };($scanner:expr, $type:ty) => { $scanner .next::<$type>() .expect(concat!("failed to read token of type ", stringify!($type))) };($scanner:expr, $type:ty; $n:expr) => { (0..$n).map(|_| scan!($scanner)).collect::<Vec<$type>>() };($scanner:expr, $($type:ty),+) => { ($( scan!($scanner, $type), )+) };} }
#[rustfmt::skip] mod writer {use std::fmt::Display;use std::io::{stdout, BufWriter, Error as IoError, Stdout, Write};#[derive(Debug)] pub struct Writer<W: Write> { writer: BufWriter<W>, }  impl Writer<Stdout> { pub fn stdout() -> Self { Self::new(stdout()) } }  impl<W: Write> Writer<W> { pub fn new(writer: W) -> Self { Self { writer: BufWriter::new(writer), } }  pub fn write<M, T: Writable<M>>(&mut self, val: T) -> Result<(), IoError> { val.write_to(&mut self.writer) }  pub fn flush(&mut self) -> Result<(), IoError> { self.writer.flush() } }  pub trait Writable<Mode> { fn write_to<W: Write>(self, w: &mut W) -> Result<(), IoError>;}  #[non_exhaustive] pub struct Single;impl<T: Display> Writable<Single> for T { fn write_to<W: Write>(self, w: &mut W) -> Result<(), IoError> { writeln!(w, "{}", self) } }  #[non_exhaustive] pub struct Many;impl<I> Writable<Many> for I where I: Iterator, I::Item: Display, { fn write_to<W: Write>(mut self, w: &mut W) -> Result<(), IoError> { if let Some(x) = self.next() { write!(w, "{}", x)?;} else {  return Ok(());}  for x in self { write!(w, " {}", x)?;} writeln!(w) } }  #[non_exhaustive] pub struct Array;impl<T: Display> Writable<Array> for &[T] { fn write_to<W: Write>(self, w: &mut W) -> Result<(), IoError> { self.iter().write_to(w) } } }
#[rustfmt::skip] mod util {   pub trait IntoVec<T, _Hack> { fn into_vec(self) -> Vec<T>;}  #[non_exhaustive] pub struct Owned;impl<I, T> IntoVec<T, Owned> for I where I: Iterator<Item = T>, { fn into_vec(self) -> Vec<T> { self.collect() } }  #[non_exhaustive] pub struct Reference;impl<'a, I, T> IntoVec<T, Reference> for I where I: Iterator<Item = &'a T>, T: Clone + 'a, { fn into_vec(self) -> Vec<T> { self.cloned().collect() } }  pub trait Argmax { fn argmax(self) -> Option<usize>;}  impl<I> Argmax for I where I: Iterator, I::Item: Ord, { fn argmax(self) -> Option<usize> { self.fold((0, None), |(i, mx), next| { if let Some((mx_i, mx_v)) = mx { if next.gt(&mx_v) { (i + 1, Some((i, next))) } else { (i + 1, Some((mx_i, mx_v))) } } else { (i + 1, Some((i, next))) } }) .1 .map(|x| x.0) } }  pub trait Sorted { fn sorted(self) -> Self;}  impl<T> Sorted for Vec<T> where T: Ord, { fn sorted(mut self) -> Self { self.sort();self } }  pub trait Choose { fn choose<T>(self, a: T, b: T) -> T;}  impl Choose for bool { fn choose<T>(self, a: T, b: T) -> T { if self { a } else { b } } } }

use prefix_sum::{CreatePrefixOps, CreatePrefixSums, CreatePrefixMax, CreatePrefixMin};
use scanner::Scanner;
use writer::Writer;
use util::{IntoVec, Argmax, Sorted, Choose};

const MOD: i64 = 1_000_000_007;
fn main() {
    let mut sc = Scanner::stdin();
    let mut wr = Writer::stdout();
    for _ in 0..scan!(sc, usize) {
        let (n, k) = scan!(sc, i64, i64);

        if n % 2 == 0 {
            let mut total = 0;
            let a = modexp(2, n - 1) - 1;
            let b = modexp(2, n);
            for i in 0..k {
                total = (total + modexp(a, i) * modexp(b, k - i - 1)) % MOD;
            }
            total = (total + modexp(a, k)) % MOD;
            wr.write(total).unwrap();
        } else {
            let c = (modexp(2, n - 1) - 1 + 2 * (n % 2)) % MOD;
            let total = modexp(c, k);
            wr.write(total).unwrap();
        }
    }
}

const fn modexp(a: i64, b: i64) -> i64 {
    if b == 0 { 1 }
    else if b % 2 == 0 { modexp((a * a) % MOD, b / 2) }
    else { (modexp((a * a) % MOD, b / 2) * a) % MOD}
}

const fn modinv(a: i64) -> i64 {
    modexp(a, MOD - 2)
}


/*
    date   : 2021 / 4 / 7
    author : quickn (quickn.tech)
    email  : quickwshell@gmail.com
*/

use std::io::{self, BufWriter, Write};

mod scanner {
    use std::{io, str};
    /* https://github.com/EbTech/rust-algorithms */

    /// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts
    /// **REQUIRES** Rust 1.34 or higher
    pub struct UnsafeScanner<R> {
        reader: R,
        buf_str: Vec<u8>,
        buf_iter: str::SplitAsciiWhitespace<'static>,
    }

    impl<R: io::BufRead> UnsafeScanner<R> {
        pub fn new(reader: R) -> Self {
            Self {
                reader,
                buf_str: Vec::new(),
                buf_iter: "".split_ascii_whitespace(),
            }
        }

        /// This function should be marked unsafe, but noone has time for that in a
        /// programming contest. Use at your own risk!
        pub fn token<T: 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 = str::from_utf8_unchecked(&self.buf_str);
                    std::mem::transmute(slice.split_ascii_whitespace())
                }
            }
        }
    }
}

use std::cmp::{min, max};

fn s2vec(s: String) -> Vec<char> {
    s.chars().collect()
}

const MOD: i64 = 1000000007;

fn pow_mod(a: i64, x: i64) -> i64 {
    let (mut a_t, mut x_t, mut r) = (a, x, 1);
    while x_t > 0 {
        if x_t % 2 == 1 {
            r *= a_t;
            r %= MOD;
        }
        a_t *= a_t;
        a_t %= MOD;
        x_t /= 2;
    }
    r
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let (mut scan, mut sout) = (
        scanner::UnsafeScanner::new(stdin.lock()),
        BufWriter::new(stdout.lock()),
    );
    let t: usize = scan.token();
    for _case in 0..t {
        let (n, k): (usize, usize) = (scan.token(), scan.token());
        if k > 0 {
        let mut dp: Vec<Vec<i64>> = vec![vec![0;2];k+1];
        dp[1][0] = pow_mod(2, (n-1) as i64) - if n % 2 == 0 { 1 } else { 0 };
        dp[1][1] = 1;
        for i in 2..=k {
            dp[i][0] = (((dp[i-1][0] + dp[i-1][1])%MOD)*(pow_mod(2, (n-1) as i64) - if n % 2 == 0 { 1 } else { 0 }))%MOD;
            if n % 2 == 0 {
                dp[i][1] = pow_mod(2, (n as i64)*((i-1) as i64));
            } else {
                dp[i][1] = (dp[i-1][1] + dp[i-1][0])%MOD;
            }
        }
        writeln!(sout, "{}", (dp[k][0] + dp[k][1])%MOD).ok();
        } else {
            writeln!(sout, "1").ok();
        }
    }
}


#![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)*N)) % 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())
            }
        }
    }
}