Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a trait for perfect power checking #233

Open
cmpute opened this issue Jan 26, 2022 · 0 comments
Open

Add a trait for perfect power checking #233

cmpute opened this issue Jan 26, 2022 · 0 comments

Comments

@cmpute
Copy link

cmpute commented Jan 26, 2022

I propose to add the following trait to support perfect power checking (especially perfect square checking)

pub trait ExactRoots : Roots + Pow<u32, Output = Self> {
    fn nth_root_exact(&self, n: u32) -> Option<Self> {
        let r = self.nth_root(n);
        if &r.pow(n) == self { Some(r) } else { None }
    }
    fn sqrt_exact(&self) -> Option<Self> { self.nth_root_exact(2) }
    fn cbrt_exact(&self) -> Option<Self> { self.nth_root_exact(3) }
    fn is_nth_power(&self, n: u32) -> bool { self.nth_root_exact(n).is_some() }
    fn is_square(&self) -> bool { self.sqrt_exact().is_some() }
    fn is_cubic(&self) -> bool { self.cbrt_exact().is_some() }
}

Fast perfect square checking can be implemented for primitive types (and also possibly big integers) using modular arithmetics. These functions can be useful in number theory related calculations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant