結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー 👑 MizarMizar
提出日時 2022-08-23 12:11:28
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 13 ms / 9,973 ms
コード長 32,583 bytes
コンパイル時間 11,895 ms
コンパイル使用メモリ 377,704 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2024-11-16 23:55:16
合計ジャッジ時間 12,956 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 0 ms
5,248 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 1 ms
5,248 KB
testcase_03 AC 1 ms
5,248 KB
testcase_04 AC 10 ms
5,248 KB
testcase_05 AC 10 ms
5,248 KB
testcase_06 AC 8 ms
5,248 KB
testcase_07 AC 8 ms
5,248 KB
testcase_08 AC 8 ms
5,248 KB
testcase_09 AC 13 ms
5,248 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

// -*- coding:utf-8-unix -*-

use std::io::{BufRead,Write};

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

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

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

trait Change { fn chmax(&mut self, x: Self); fn chmin(&mut self, x: Self); }
impl<T: std::cmp::PartialOrd> Change for T {
    fn chmax(&mut self, x: T) { if *self < x { *self = x; } }
    fn chmin(&mut self, x: T) { if *self > x { *self = x; } }
}

// Integer Wrapper Traits
pub trait Zero { fn zero() -> Self; fn is_zero(&self) -> bool; }
pub trait One { fn one() -> Self; }
pub trait TrailingZeros { fn trailing_zeros(&self) -> u32; }
pub trait WrappingAdd { fn wrapping_add(&self, v: &Self) -> Self; }
pub trait WrappingSub { fn wrapping_sub(&self, v: &Self) -> Self; }
pub trait WrappingMul { fn wrapping_mul(&self, v: &Self) -> Self; }
pub trait WrappingNeg { fn wrapping_neg(&self) -> Self; }
pub trait IntNum:
    Copy
    + Eq
    + Ord
    + Zero
    + One
    + TrailingZeros
    + WrappingAdd
    + WrappingSub
    + WrappingMul
    + WrappingNeg
    + std::marker::Sized
    + std::ops::Add<Output = Self>
    + std::ops::AddAssign
    + std::ops::Sub<Output = Self>
    + std::ops::SubAssign
    + std::ops::Mul<Output = Self>
    + std::ops::Div<Output = Self>
    + std::ops::Rem<Output = Self>
    + std::ops::BitAnd<Output = Self>
    + std::ops::Shl<Output = Self>
    + std::ops::ShlAssign
    + std::ops::Shr<Output = Self>
    + std::ops::ShrAssign
    + std::fmt::Debug
{
}
pub trait UIntNum: IntNum {}
pub trait IIntNum: IntNum {}
macro_rules! define_zero_one {
    ($ty:ty, $zero:expr, $one:expr) => {
        impl Zero for $ty {
            #[inline]
            fn zero() -> Self {
                $zero
            }
            #[inline]
            fn is_zero(&self) -> bool {
                *self == $zero
            }
        }
        impl One for $ty {
            #[inline]
            fn one() -> Self {
                $one
            }
        }
    };
}
define_zero_one!(usize, 0, 1);
define_zero_one!(u8, 0, 1);
define_zero_one!(u16, 0, 1);
define_zero_one!(u32, 0, 1);
define_zero_one!(u64, 0, 1);
define_zero_one!(u128, 0, 1);
define_zero_one!(isize, 0, 1);
define_zero_one!(i8, 0, 1);
define_zero_one!(i16, 0, 1);
define_zero_one!(i32, 0, 1);
define_zero_one!(i64, 0, 1);
define_zero_one!(i128, 0, 1);
define_zero_one!(f32, 0.0, 1.0);
define_zero_one!(f64, 0.0, 1.0);
macro_rules! integer_bitcount_impl {
    ($trait_name:ident, $method:ident, $t:ty) => {
        impl $trait_name for $t {
            #[inline]
            fn $method(&self) -> u32 {
                <$t>::$method(*self)
            }
        }
    };
}
macro_rules! integer_wrapping_impl {
    ($trait_name:ident, $method:ident, $t:ty) => {
        impl $trait_name for $t {
            #[inline]
            fn $method(&self, v: &Self) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    };
    ($trait_name:ident, $method:ident, $t:ty, $rhs:ty) => {
        impl $trait_name<$rhs> for $t {
            #[inline]
            fn $method(&self, v: &$rhs) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    };
}
macro_rules! integer_wrapping_impl1 {
    ($trait_name:ident, $method:ident, $t:ty) => {
        impl $trait_name for $t {
            #[inline]
            fn $method(&self) -> Self {
                <$t>::$method(*self)
            }
        }
    };
}
integer_bitcount_impl!(TrailingZeros, trailing_zeros, u8);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, u16);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, u32);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, u64);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, u128);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, usize);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, i8);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, i16);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, i32);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, i64);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, i128);
integer_bitcount_impl!(TrailingZeros, trailing_zeros, isize);
integer_wrapping_impl!(WrappingAdd, wrapping_add, u8);
integer_wrapping_impl!(WrappingAdd, wrapping_add, u16);
integer_wrapping_impl!(WrappingAdd, wrapping_add, u32);
integer_wrapping_impl!(WrappingAdd, wrapping_add, u64);
integer_wrapping_impl!(WrappingAdd, wrapping_add, u128);
integer_wrapping_impl!(WrappingAdd, wrapping_add, usize);
integer_wrapping_impl!(WrappingAdd, wrapping_add, i8);
integer_wrapping_impl!(WrappingAdd, wrapping_add, i16);
integer_wrapping_impl!(WrappingAdd, wrapping_add, i32);
integer_wrapping_impl!(WrappingAdd, wrapping_add, i64);
integer_wrapping_impl!(WrappingAdd, wrapping_add, i128);
integer_wrapping_impl!(WrappingAdd, wrapping_add, isize);
integer_wrapping_impl!(WrappingSub, wrapping_sub, u8);
integer_wrapping_impl!(WrappingSub, wrapping_sub, u16);
integer_wrapping_impl!(WrappingSub, wrapping_sub, u32);
integer_wrapping_impl!(WrappingSub, wrapping_sub, u64);
integer_wrapping_impl!(WrappingSub, wrapping_sub, u128);
integer_wrapping_impl!(WrappingSub, wrapping_sub, usize);
integer_wrapping_impl!(WrappingSub, wrapping_sub, i8);
integer_wrapping_impl!(WrappingSub, wrapping_sub, i16);
integer_wrapping_impl!(WrappingSub, wrapping_sub, i32);
integer_wrapping_impl!(WrappingSub, wrapping_sub, i64);
integer_wrapping_impl!(WrappingSub, wrapping_sub, i128);
integer_wrapping_impl!(WrappingSub, wrapping_sub, isize);
integer_wrapping_impl!(WrappingMul, wrapping_mul, u8);
integer_wrapping_impl!(WrappingMul, wrapping_mul, u16);
integer_wrapping_impl!(WrappingMul, wrapping_mul, u32);
integer_wrapping_impl!(WrappingMul, wrapping_mul, u64);
integer_wrapping_impl!(WrappingMul, wrapping_mul, u128);
integer_wrapping_impl!(WrappingMul, wrapping_mul, usize);
integer_wrapping_impl!(WrappingMul, wrapping_mul, i8);
integer_wrapping_impl!(WrappingMul, wrapping_mul, i16);
integer_wrapping_impl!(WrappingMul, wrapping_mul, i32);
integer_wrapping_impl!(WrappingMul, wrapping_mul, i64);
integer_wrapping_impl!(WrappingMul, wrapping_mul, i128);
integer_wrapping_impl!(WrappingMul, wrapping_mul, isize);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, u8);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, u16);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, u32);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, u64);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, u128);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, usize);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, i8);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, i16);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, i32);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, i64);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, i128);
integer_wrapping_impl1!(WrappingNeg, wrapping_neg, isize);
impl IntNum for usize {}
impl IntNum for u8 {}
impl IntNum for u16 {}
impl IntNum for u32 {}
impl IntNum for u64 {}
impl IntNum for u128 {}
impl IntNum for isize {}
impl IntNum for i8 {}
impl IntNum for i16 {}
impl IntNum for i32 {}
impl IntNum for i64 {}
impl IntNum for i128 {}
impl UIntNum for usize {}
impl UIntNum for u8 {}
impl UIntNum for u16 {}
impl UIntNum for u32 {}
impl UIntNum for u64 {}
impl UIntNum for u128 {}
impl IIntNum for isize {}
impl IIntNum for i8 {}
impl IIntNum for i16 {}
impl IIntNum for i32 {}
impl IIntNum for i64 {}
impl IIntNum for i128 {}

// モンゴメリ剰余乗算 (Montgomery modular multiplication)
pub trait UMontTrait<T: UIntNum> {
    fn n(&self) -> T;
    fn ni(&self) -> T;
    fn r(&self) -> T;
    fn r2(&self) -> T;
    fn d(&self) -> T;
    fn k(&self) -> u32;
    fn new(n: T) -> Self;
    fn addmod(&self, a: T, b: T) -> T;
    fn submod(&self, a: T, b: T) -> T;
    #[inline]
    fn div2(&self, ar: T) -> T {
        // == ar / 2 (mod n)
        if (ar & T::one()).is_zero() {
            ar >> T::one()
        } else {
            (ar >> T::one()) + (((self.n()) >> T::one()) + T::one())
        }
    }
    fn mrmul(&self, ar: T, br: T) -> T;
    fn mr(&self, ar: T) -> T;
    #[inline]
    fn ar(&self, a: T) -> T {
        // == a * r (mod n)
        debug_assert!(a < self.n());
        self.mrmul(a, self.r2())
    }
    #[inline]
    fn powir(&self, mut ar: T, mut b: T) -> T {
        // == ((ar / r) ** b) * r (mod n)
        debug_assert!(ar < self.n());
        let mut t = if (b & T::one()).is_zero() { self.r() } else { ar };
        b >>= T::one();
        while !b.is_zero() {
            ar = self.mrmul(ar, ar);
            t = self.mrmul(t, if (b & T::one()).is_zero() { self.r() } else { ar });
            b >>= T::one();
        }
        t
    }
    fn prime_test_once(&self, base: T) -> bool {
        // Miller-Rabin primality test
        debug_assert!(base > T::one());
        let (n, r, d, k) = (self.n(), self.r(), self.d(), self.k());
        let b = base % n;
        if b.is_zero() { return true; }
        let mut br = self.powir(self.ar(b), d);
        if br == r { return true; }
        let negr = n - r;
        for _ in 0..k {
            if br == negr { return true; }
            br = self.mrmul(br, br);
        }
        false
    }
}
pub struct U64Mont {
    n: u64, // n is odd, and n > 2
    ni: u64, // n * ni == 1 (mod 2**64)
    r: u64, // == 2**64 (mod n)
    r2: u64, // == 2**128 (mod n)
    d: u64, // == (n - 1) >> (n - 1).trailing_zeros()
    k: u32, // == (n - 1).trailing_zeros()
}
impl UMontTrait<u64> for U64Mont {
    #[inline] fn n(&self) -> u64 { self.n }
    #[inline] fn ni(&self) -> u64 { self.ni }
    #[inline] fn r(&self) -> u64 { self.r }
    #[inline] fn r2(&self) -> u64 { self.r2 }
    #[inline] fn d(&self) -> u64 { self.d }
    #[inline] fn k(&self) -> u32 { self.k }
    #[inline]
    fn new(n: u64) -> Self {
        debug_assert_eq!(n & 1, 1);
        // // n is odd number, n = 2*k+1, n >= 1, n < 2**64, k is non-negative integer, k >= 0, k < 2**63
        // ni0 := n; // = 2*k+1 = (1+(2**2)*((k*(k+1))**1))/(2*k+1)
        let mut ni = n;
        // ni1 := ni0 * (2 - (n * ni0)); // = (1-(2**4)*((k*(k+1))**2))/(2*k+1)
        // ni2 := ni1 * (2 - (n * ni1)); // = (1-(2**8)*((k*(k+1))**4))/(2*k+1)
        // ni3 := ni2 * (2 - (n * ni2)); // = (1-(2**16)*((k*(k+1))**8))/(2*k+1)
        // ni4 := ni3 * (2 - (n * ni3)); // = (1-(2**32)*((k*(k+1))**16))/(2*k+1)
        // ni5 := ni4 * (2 - (n * ni4)); // = (1-(2**64)*((k*(k+1))**32))/(2*k+1)
        // // (n * ni5) mod 2**64 = ((2*k+1) * ni5) mod 2**64 = 1 mod 2**64
        for _ in 0..5 {
            ni = ni.wrapping_mul(2u64.wrapping_sub(n.wrapping_mul(ni)));
        }
        debug_assert_eq!(n.wrapping_mul(ni), 1); // n * ni == 1 (mod 2**64)
        let r: u64 = n.wrapping_neg() % n; // == 2**64 (mod n)
        let r2: u64 = ((n as u128).wrapping_neg() % (n as u128)) as u64; // == 2**128 (mod n)
        let mut d = n - 1;
        let k = d.trailing_zeros();
        d >>= k;
        debug_assert_eq!(Self { n, ni, r, r2, d, k }.mr(r), 1); // r / r == 1 (mod n)
        debug_assert_eq!(Self { n, ni, r, r2, d, k }.mrmul(1, r2), r); // r2 / r == r (mod n)
        Self { n, ni, r, r2, d, k }
    }
    #[inline]
    fn addmod(&self, a: u64, b: u64) -> u64 {
        // == a + b (mod n)
        debug_assert!(a < self.n);
        debug_assert!(b < self.n);
        let t: (u64, bool) = a.overflowing_add(b);
        let u: (u64, bool) = t.0.overflowing_sub(self.n);
        if t.1 || !(u.1) { u.0 } else { t.0 }
    }
    #[inline]
    fn submod(&self, a: u64, b: u64) -> u64 {
        // == a - b (mod n)
        debug_assert!(a < self.n);
        debug_assert!(b < self.n);
        let t: (u64, bool) = a.overflowing_sub(b);
        if t.1 { t.0.wrapping_add(self.n) } else { t.0 }
    }
    #[inline]
    fn mrmul(&self, ar: u64, br: u64) -> u64 {
        // == (ar * br) / r (mod n)
        debug_assert!(ar < self.n);
        debug_assert!(br < self.n);
        let (n, ni) = (self.n, self.ni);
        let t: u128 = (ar as u128) * (br as u128);
        let t: (u64, bool) = ((t >> 64) as u64).overflowing_sub((((((t as u64).wrapping_mul(ni)) as u128) * (n as u128)) >> 64) as u64);
        if t.1 { t.0.wrapping_add(n) } else { t.0 }
    }
    #[inline]
    fn mr(&self, ar: u64) -> u64 {
        // == ar / r (mod n)
        debug_assert!(ar < self.n);
        let (n, ni) = (self.n, self.ni);
        let t: (u64, bool) = (((((ar.wrapping_mul(ni)) as u128) * (n as u128)) >> 64) as u64).overflowing_neg();
        if t.1 { t.0.wrapping_add(n) } else { t.0 }
    }
}
pub struct U32Mont {
    n: u32, // n is odd, and n > 2
    ni: u32, // n * mi == 1 (mod 2**32)
    r: u32, // == 2**32 (mod n)
    r2: u32, // == 2**64 (mod n)
    d: u32, // == (n - 1) >> (n - 1).trailing_zeros()
    k: u32, // == (n - 1).trailing_zeros()
}
impl UMontTrait<u32> for U32Mont {
    #[inline] fn n(&self) -> u32 { self.n }
    #[inline] fn ni(&self) -> u32 { self.ni }
    #[inline] fn r(&self) -> u32 { self.r }
    #[inline] fn r2(&self) -> u32 { self.r2 }
    #[inline] fn d(&self) -> u32 { self.d }
    #[inline] fn k(&self) -> u32 { self.k }
    #[inline]
    fn new(n: u32) -> Self {
        debug_assert_eq!(n & 1, 1);
        // // n is odd number, n = 2*k+1, n >= 1, n < 2**64, k is non-negative integer, k >= 0, k < 2**63
        // ni0 := n; // = 2*k+1 = (1+(2**2)*((k*(k+1))**1))/(2*k+1)
        let mut ni = n;
        // ni1 := ni0 * (2 - (n * ni0)); // = (1-(2**4)*((k*(k+1))**2))/(2*k+1)
        // ni2 := ni1 * (2 - (n * ni1)); // = (1-(2**8)*((k*(k+1))**4))/(2*k+1)
        // ni3 := ni2 * (2 - (n * ni2)); // = (1-(2**16)*((k*(k+1))**8))/(2*k+1)
        // ni4 := ni3 * (2 - (n * ni3)); // = (1-(2**32)*((k*(k+1))**16))/(2*k+1)
        // // (n * ni4) mod 2**32 = ((2*k+1) * ni4) mod 2**32 = 1 mod 2**32
        for _ in 0..4 {
            ni = ni.wrapping_mul(2u32.wrapping_sub(n.wrapping_mul(ni)));
        }
        debug_assert_eq!(n.wrapping_mul(ni), 1); // n * ni == 1 (mod 2**32)
        let r: u32 = n.wrapping_neg() % n; // == 2**64 (mod n)
        let r2: u32 = ((n as u64).wrapping_neg() % (n as u64)) as u32; // == 2**64 (mod n)
        let mut d = n - 1;
        let k = d.trailing_zeros();
        d >>= k;
        debug_assert_eq!(Self { n, ni, r, r2, d, k }.mr(r), 1); // r / r == 1 (mod n)
        debug_assert_eq!(Self { n, ni, r, r2, d, k }.mrmul(1, r2), r); // r2 / r == r (mod n)
        Self { n, ni, r, r2, d, k }
    }
    #[inline]
    fn addmod(&self, a: u32, b: u32) -> u32 {
        // == a + b (mod n)
        debug_assert!(a < self.n);
        debug_assert!(b < self.n);
        let t: (u32, bool) = a.overflowing_add(b);
        let u: (u32, bool) = t.0.overflowing_sub(self.n);
        if t.1 || !(u.1) { u.0 } else { t.0 }
    }
    #[inline]
    fn submod(&self, a: u32, b: u32) -> u32 {
        // == a - b (mod n)
        debug_assert!(a < self.n);
        debug_assert!(b < self.n);
        let t: (u32, bool) = a.overflowing_sub(b);
        if t.1 { t.0.wrapping_add(self.n) } else { t.0 }
    }
    #[inline]
    fn mrmul(&self, ar: u32, br: u32) -> u32 {
        // == (ar * br) / r (mod n)
        debug_assert!(ar < self.n);
        debug_assert!(br < self.n);
        let (n, ni) = (self.n, self.ni);
        let t: u64 = (ar as u64) * (br as u64);
        let t: (u32, bool) = ((t >> 32) as u32).overflowing_sub((((((t as u32).wrapping_mul(ni)) as u64) * (n as u64)) >> 32) as u32);
        if t.1 { t.0.wrapping_add(n) } else { t.0 }
    }
    #[inline]
    fn mr(&self, ar: u32) -> u32 {
        // == ar / r (mod n)
        debug_assert!(ar < self.n);
        let (n, ni) = (self.n, self.ni);
        let t: (u32, bool) = (((((ar.wrapping_mul(ni)) as u64) * (n as u64)) >> 32) as u32).overflowing_neg();
        if t.1 { t.0.wrapping_add(n) } else { t.0 }
    }
}

// 64bit整数平方根(固定ループ回数) -> (floor(sqrt(iv)), remain)
#[allow(unused)]
#[inline]
fn isqrt64f(iv: u64) -> (u64, u64) { isqrt64i(iv, 0) }
// 64bit整数平方根(可変ループ回数) -> (floor(sqrt(iv)), remain)
#[allow(unused)]
#[inline]
fn isqrt64d(iv: u64) -> (u64, u64) { isqrt64i(iv, iv.leading_zeros()) }
// 64bit整数平方根(lz:ケチるループ回数*2+(0~1)、内部実装) -> (floor(sqrt(iv)), remain)
#[inline]
fn isqrt64i(iv: u64, lz: u32) -> (u64, u64) {
    let n = (64 >> 1) - (lz >> 1);
    let s = (lz >> 1) << 1;
    let t = n << 1;
    let (mut a, mut b, c, d, e) = (
        iv as u128,
        0x0000_0000_0000_0000_4000_0000_0000_0000 >> s,
        0xffff_ffff_ffff_fffe_0000_0000_0000_0000 >> s,
        0x0000_0000_0000_0001_0000_0000_0000_0000 >> s,
        0x0000_0000_0000_0000_ffff_ffff_ffff_ffff >> s,
    );
    for _ in 0..n {
        if a >= b {
            a -= b;
            b = ((b + b) & c) + d + (b & e);
        } else {
            b = ((b + b) & c) + (b & e);
        }
        a <<= 2;
    }
    ((b >> t) as u64, (a >> t) as u64)
}

// Jacobi symbol: ヤコビ記号
#[inline]
fn jacobi(a: i64, mut n: u64) -> i32 {
    let (mut a, mut j): (u64, i32) = if a >= 0 { (a as u64, 1) } else if (n & 3) == 3 { ((-a) as u64, -1) } else { ((-a) as u64, 1) };
    while a > 0 {
        let ba = a.trailing_zeros();
        a >>= ba;
        if ((n & 7) == 3 || (n & 7) == 5) && (ba & 1) == 1 { j = -j; }
        if (a & n & 3) == 3 { j = -j; }
        let t = a; a = n; n = t; a %= n;
        if a > (n >> 1) {
            a = n - a;
            if (n & 3) == 3 { j = -j; }
        }
    }
    if n == 1 { j } else { 0 }
}

#[inline]
fn prime_test_base2(u64mont: &U64Mont) -> bool {
    // Mirrer-Rabin primality test (base 2)
    // strong pseudoprimes to base 2 ( https://oeis.org/A001262 ): 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, ...
    u64mont.prime_test_once(2)
}

#[allow(unused)]
#[inline]
fn prime_test_3bases(u64mont: &U64Mont) -> bool {
    assert!(u64mont.n <= 350269456337);
    u64mont.prime_test_once(4230279247111683200) &&
    u64mont.prime_test_once(14694767155120705706) &&
    u64mont.prime_test_once(16641139526367750375)
}

#[allow(unused)]
#[inline]
fn prime_test_7bases(u64mont: &U64Mont) -> bool {
    u64mont.prime_test_once(2) &&
    u64mont.prime_test_once(325) &&
    u64mont.prime_test_once(9375) &&
    u64mont.prime_test_once(28178) &&
    u64mont.prime_test_once(450775) &&
    u64mont.prime_test_once(9780504) &&
    u64mont.prime_test_once(1795265022)
}

fn prime_test_lucas(u64mont: &U64Mont) -> bool {
    // Lucas primality test
    // strong Lucas pseudoprimes ( https://oeis.org/A217255 ): 5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309, 58519, ...
    let n = u64mont.n;
    let mut d: i64 = 5;
    for i in 0..64 {
        if jacobi(d, n) == -1 { break; }
        if i == 32 && isqrt64f(n).1 == 0 { return false; }
        if (i & 1) == 1 { d = 2 - d; } else { d = -(d + 2); }
    }
    let qm = u64mont.ar(if d < 0 {((1 - d) as u64) / 4 % n} else {n - ((d - 1) as u64) / 4 % n});
    let mut k = (n + 1) << (n + 1).leading_zeros();
    let mut um = u64mont.r;
    let mut vm = u64mont.r;
    let mut qn = qm;
    let dm: u64 = u64mont.ar(if d < 0 { let nd = ((-d) as u64) % n; if nd == 0 { 0 } else { n - nd } } else { (d as u64) % n });
    k <<= 1;
    while k > 0 {
        um = u64mont.mrmul(um, vm);
        vm = u64mont.submod(u64mont.mrmul(vm, vm), u64mont.addmod(qn, qn));
        qn = u64mont.mrmul(qn, qn);
        if (k >> 63) != 0 {
            let mut uu = u64mont.addmod(um, vm);
            uu = u64mont.div2(uu);
            vm = u64mont.addmod(u64mont.mrmul(dm, um), vm);
            vm = u64mont.div2(vm);
            um = uu;
            qn = u64mont.mrmul(qn, qm);
        }
        k <<= 1;
    }
    if um == 0 || vm == 0 {
        return true;
    }
    let mut x = (n + 1) & (!n);
    x >>= 1;
    while x > 0 {
        um = u64mont.mrmul(um, vm);
        vm = u64mont.submod(u64mont.mrmul(vm, vm), u64mont.addmod(qn, qn));
        if vm == 0 {
            return true;
        }
        qn = u64mont.mrmul(qn, qn);
        x >>= 1;
    }
    false
}

// Baillie–PSW primarity test
pub fn prime_test_bpsw(n: u64) -> bool {
    if n == 2 { return true; }
    if n == 1 || (n & 1) == 0 { return false; }
    let u64mont = U64Mont::new(n);
    // Mirrer-Rabin primality test (base 2)
    // strong pseudoprimes to base 2 ( https://oeis.org/A001262 ): 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, ...
    prime_test_base2(&u64mont) &&
    // Lucas primality test
    // strong Lucas pseudoprimes ( https://oeis.org/A217255 ): 5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309, 58519, ...
    prime_test_lucas(&u64mont)
}

pub fn prime_test_32(n: u32) -> bool {
    if n == 2 { return true; }
    if n == 1 || (n & 1) == 0 { return false; }
    let u32mont = U32Mont::new(n);
    match n {
        // Deterministic variants of the Miller-Rabin primality test
        // http://miller-rabin.appspot.com/
        0..=49141 => {
            u32mont.prime_test_once(921211727)
        },
        0..=360018361 => {
            u32mont.prime_test_once(1143370) &&
            u32mont.prime_test_once(2350307676)
        },
        _ => {
            u32mont.prime_test_once(2) &&
            u32mont.prime_test_once(7) &&
            u32mont.prime_test_once(61)
        }
    }
}
pub fn prime_test_64(n: u64) -> bool {
    if n == 2 { return true; }
    if n == 1 || (n & 1) == 0 { return false; }
    let u64mont = U64Mont::new(n);
    match n {
        // Deterministic variants of the Miller-Rabin primality test
        // http://miller-rabin.appspot.com/
        0..=341531 => {
            u64mont.prime_test_once(9345883071009581737)
        },
        0..=1050535501 => {
            u64mont.prime_test_once(336781006125) &&
            u64mont.prime_test_once(9639812373923155)
        },
        0..=350269456337 => {
            u64mont.prime_test_once(4230279247111683200) &&
            u64mont.prime_test_once(14694767155120705706) &&
            u64mont.prime_test_once(16641139526367750375)
        },
        0..=55245642489451 => {
            u64mont.prime_test_once(2) &&
            u64mont.prime_test_once(141889084524735) &&
            u64mont.prime_test_once(1199124725622454117) &&
            u64mont.prime_test_once(11096072698276303650)
        },
        0..=7999252175582851 => {
            u64mont.prime_test_once(2) &&
            u64mont.prime_test_once(4130806001517) &&
            u64mont.prime_test_once(149795463772692060) &&
            u64mont.prime_test_once(186635894390467037) &&
            u64mont.prime_test_once(3967304179347715805)
        },
        0..=585226005592931977 => {
            u64mont.prime_test_once(2) &&
            u64mont.prime_test_once(123635709730000) &&
            u64mont.prime_test_once(9233062284813009) &&
            u64mont.prime_test_once(43835965440333360) &&
            u64mont.prime_test_once(761179012939631437) &&
            u64mont.prime_test_once(1263739024124850375)
        },
        _ => {
            u64mont.prime_test_once(2) &&
            u64mont.prime_test_once(325) &&
            u64mont.prime_test_once(9375) &&
            u64mont.prime_test_once(28178) &&
            u64mont.prime_test_once(450775) &&
            u64mont.prime_test_once(9780504) &&
            u64mont.prime_test_once(1795265022)
        },
    }
}

fn main() {
    let start_time = std::time::Instant::now();
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    macro_rules! puts {($($format:tt)*) => (let _ = write!(out,$($format)*););}
    /*
    input! {
        n: usize,
        x: [u64; n],
    }
    */
    let input = std::io::stdin();
    let mut lines = std::io::BufReader::new(input.lock()).lines();
    let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
    /*
    let x: Vec<u64> = lines.take(n).map(|l| l.unwrap().parse().unwrap()).collect();
    let elapsed1 = start_time.elapsed();
    let res: Vec<bool> = x.iter().map(|&v| prime_test_bpsw(v)).collect();
    let elapsed2 = start_time.elapsed();
    for i in 0..n {
        puts!("{} {}\n", x[i], if res[i] { "1" } else { "0" });
    }
    let elapsed3 = start_time.elapsed();
    out.flush().unwrap();
    let elapsed4 = start_time.elapsed();
    eprint!(
        "  input: {}us\ncompute: {}us\n output: {}us\n wflush: {}us\n",
        elapsed1.as_micros(),
        elapsed2.as_micros(),
        elapsed3.as_micros(),
        elapsed4.as_micros(),
    );
    */
    for _ in 0..n {
        let x: u64 = lines.next().unwrap().unwrap().parse().unwrap();
        puts!("{} {}\n", x, if prime_test_bpsw(x) { "1" } else { "0" });
    }
    eprint!("{}us\n", start_time.elapsed().as_micros());
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn test_base2() {
        // Mirrer-Rabin primality test (base 2)
        // strong pseudoprimes to base 2 ( https://oeis.org/A001262 ): 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, ...
        // composite 2-SPRP list up to 2**64 ( http://miller-rabin.appspot.com/#links )
        // Pseudoprime Statistics, Tables, and Data ( http://ntheory.org/pseudoprimes.html )
        // Miller-Rabin base 2 data (up to 1e15) ( http://ntheory.org/data/spsps.txt )
        let assumed: Vec<u64> = vec![
            2047,3277,4033,4681,8321,15841,29341,42799,49141,52633,65281,74665,80581,85489,88357,90751,104653,130561,
            196093,220729,233017,252601,253241,256999,271951,280601,314821,357761,390937,458989,476971,486737,489997,
            514447,580337,635401,647089,741751,800605,818201,838861,873181,877099,916327,976873,983401,1004653,1016801,
            1023121,1082401,1145257,1194649,1207361,1251949,1252697,1302451,1325843,1357441,1373653,1397419,1441091,
            1493857,1507963,1509709,1530787,1678541,1730977,1811573,1876393,1907851,1909001,1969417,1987021,2004403,
            2081713,2181961,2205967,2264369,2269093,2284453,2304167,2387797,2419385,2510569,2746477,2748023,2757241,
            2811271,2909197,2953711,2976487,3090091,3116107,3125281,3375041,3400013,3429037,3539101,3567481,3581761,
            3605429,3898129,4181921,4188889,4335241,4360621,4469471,4502485,4513841,4682833,4835209,4863127,5016191,
            5044033,5049001,5173169,5173601,5256091,5310721,5444489,5489641,5590621,5599765,5672041,5681809,5919187,
            6140161,6226193,6233977,6334351,6368689,6386993,6787327,6836233,6952037,7177105,7306261,7306561,7462001,
            7674967,7759937,7820201,7883731,8036033,8095447,8384513,8388607,8534233,8725753,8727391,9006401,9056501,
            9069229,9073513,9371251,9564169,9567673,9588151,9729301,9774181,9863461,9995671
        ];
        let result: Vec<u64> = (3..10_000_000).filter(|&n| n & 1 == 1).filter(|&n| {
            let u64mont = U64Mont::new(n);
            let res_3bases = prime_test_3bases(&u64mont);
            let res_base2 = prime_test_base2(&u64mont);
            assert!(!res_3bases || res_base2);
            res_3bases != res_base2
        }).collect();
        assert_eq!(assumed, result);
    }

    #[test]
    fn test_lucas() {
        // Lucas primality test
        // strong Lucas pseudoprimes ( https://oeis.org/A217255 ): 5459,5777,10877,16109,18971,22499,24569,25199,40309,58519, ...
        // Pseudoprime Statistics, Tables, and Data ( http://ntheory.org/pseudoprimes.html )
        // Strong Lucas-Selfridge data (up to 1e15) ( http://ntheory.org/data/slpsps-baillie.txt )
        let assumed: Vec<u64> = vec![
            5459,5777,10877,16109,18971,22499,24569,25199,40309,58519,75077,97439,100127,113573,115639,130139,155819,
            158399,161027,162133,176399,176471,189419,192509,197801,224369,230691,231703,243629,253259,268349,288919,
            313499,324899,353219,366799,391169,430127,436409,455519,487199,510479,572669,611399,622169,635627,636199,
            701999,794611,835999,839159,851927,871859,875879,887879,895439,950821,960859,1033997,1106327,1241099,
            1256293,1308119,1311389,1388903,1422319,1501439,1697183,1711469,1777159,1981559,2003579,2263127,2435423,
            2461211,2518889,2566409,2624399,2662277,2666711,2690759,2738969,2782079,2828699,2942081,2952071,3109049,
            3165119,3175883,3179609,3204599,3373649,3399527,3410531,3441239,3452147,3479111,3498879,3579599,3684251,
            3694079,3700559,3706169,3735521,3774377,3776219,3785699,3802499,3813011,3865319,3892529,3900797,3903791,
            4067279,4109363,4226777,4309631,4322399,4368869,4403027,4563719,4828277,4870847,5133281,5208377,5299139,
            5396999,5450201,5479109,5514479,5720219,5762629,5807759,5879411,5942627,6001379,6003923,6296291,6562891,
            6641189,6668099,6784721,6784861,6863291,6893531,6965639,7017949,7163441,7199399,7241639,7353917,7453619,
            7621499,8112899,8159759,8221121,8234159,8361989,8372849,8518127,8530559,8555009,8574551,8581219,8711699,
            8817899,8990279,9049319,9335969,9401893,9485951,9587411,9713027,9793313,9800981,9827711,9922337,9965069
        ];
        let result: Vec<u64> = (3..10_000_000).filter(|&n| n & 1 == 1).filter(|&n| {
            let u64mont = U64Mont::new(n);
            let res_3bases = prime_test_3bases(&u64mont);
            let res_lucas = prime_test_lucas(&u64mont);
            assert!(!res_3bases || res_lucas);
            res_3bases != res_lucas
        }).collect();
        assert_eq!(assumed, result);
    }

    #[test]
    fn test_bpsw_1e7() {
        for n in 3..10_000_000 {
            if (n & 1) == 0 { continue; }
            let u64mont = U64Mont::new(n);
            let res_3bases = prime_test_3bases(&u64mont);
            let res_bpsw = prime_test_base2(&u64mont) && prime_test_lucas(&u64mont);
            assert_eq!(res_3bases, res_bpsw);
        }
    }

    #[test]
    fn test_bpsw_1e15() { // 50bit
        for n in 1_000_000_000_000_000..1_000_000_010_000_000 {
            if (n & 1) == 0 { continue; }
            let u64mont = U64Mont::new(n);
            let res_7bases = prime_test_7bases(&u64mont);
            let res_bpsw = prime_test_base2(&u64mont) && prime_test_lucas(&u64mont);
            assert_eq!(res_7bases, res_bpsw);
        }
    }

    #[test]
    fn test_bpsw_9e18() { // 63bit
        for n in 9_000_000_000_000_000_000..9_000_000_000_010_000_000 {
            if (n & 1) == 0 { continue; }
            let u64mont = U64Mont::new(n);
            let res_7bases = prime_test_7bases(&u64mont);
            let res_bpsw = prime_test_base2(&u64mont) && prime_test_lucas(&u64mont);
            assert_eq!(res_7bases, res_bpsw);
        }
    }

    #[test]
    fn test_bpsw_10e18() { // 64bit
        for n in 10_000_000_000_000_000_000..10_000_000_000_010_000_000 {
            if (n & 1) == 0 { continue; }
            let u64mont = U64Mont::new(n);
            let res_7bases = prime_test_7bases(&u64mont);
            let res_bpsw = prime_test_base2(&u64mont) && prime_test_lucas(&u64mont);
            assert_eq!(res_7bases, res_bpsw);
        }
    }

    #[test]
    fn test_bpsw_18e18() { // 64bit
        for n in 18_000_000_000_000_000_000..18_000_000_000_010_000_000 {
            if (n & 1) == 0 { continue; }
            let u64mont = U64Mont::new(n);
            let res_7bases = prime_test_7bases(&u64mont);
            let res_bpsw = prime_test_base2(&u64mont) && prime_test_lucas(&u64mont);
            assert_eq!(res_7bases, res_bpsw);
        }
    }

}
0