Perfect square and perfect cube

d3vdpro picture d3vdpro · Oct 11, 2009 · Viewed 43.2k times · Source

Is there any predefined function in c++ to check whether the number is square of any number and same for the cube..

Answer

Chris Jester-Young picture Chris Jester-Young · Oct 11, 2009

No, but it's easy to write one:

bool is_perfect_square(int n) {
    if (n < 0)
        return false;
    int root(round(sqrt(n)));
    return n == root * root;
}

bool is_perfect_cube(int n) {
    int root(round(cbrt(n)));
    return n == root * root * root;
}