use crate::gaussian_integer::GaussianInteger;
use crate::integer::Integer;
use crate::natural::Natural;
use malachite_base::num::arithmetic::traits::{FloorSqrt, Square, UnsignedAbs};
use malachite_base::num::basic::traits::Zero;
pub fn gaussian_integer_checked_sqrt_naive(z: &GaussianInteger) -> Option<GaussianInteger> {
let norm: Natural =
z.real.unsigned_abs_ref().square() + z.imaginary.unsigned_abs_ref().square();
let n = Integer::from(norm.floor_sqrt());
let x = Integer::from(((&n + &z.real) >> 1u32).unsigned_abs().floor_sqrt());
let y = Integer::from(((n - &z.real) >> 1u32).unsigned_abs().floor_sqrt());
for candidate in [
GaussianInteger {
real: x.clone(),
imaginary: y.clone(),
},
GaussianInteger {
real: x,
imaginary: -y,
},
] {
if (&candidate).square() == *z {
return Some(
if (&candidate.real, &candidate.imaginary) >= (&Integer::ZERO, &Integer::ZERO) {
candidate
} else {
-candidate
},
);
}
}
None
}