Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perfect square and perfect cube

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

like image 266
d3vdpro Avatar asked Oct 11 '09 05:10

d3vdpro


2 Answers

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;
}
like image 69
Chris Jester-Young Avatar answered Sep 28 '22 06:09

Chris Jester-Young


The most efficient answer could be this

    int x=sqrt(num)
    if(sqrt(num)>x){
    Then its not a square root}
    else{it is a perfect square}

This method works because of the fact that x is an int and it will drop down the decimal part to store only the integer part. If a number is perfect square of an integer, its square root will be an integer and hence x and sqrt(x) will be equal.

like image 45
Saurabh Kumar Avatar answered Sep 28 '22 06:09

Saurabh Kumar