Perfect square and perfect cube

44,624

Solution 1

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;
}

Solution 2

sqrt(x), or in general, pow(x, 1./2) or pow(x, 1./3)

For example:

int n = 9;
int a = (int) sqrt((double) n);
if(a * a == n || (a+1) * (a+1) == n)  // in case of an off-by-one float error
    cout << "It's a square!\n";

Edit: or in general:

bool is_nth_power(int a, int n) {
  if(n <= 0)
    return false;
  if(a < 0 && n % 2 == 0)
    return false;
  a = abs(a);

  int b = pow(a, 1. / n);
  return pow((double) b, n) == a || pow((double) (b+1), n) == a;
}

Solution 3

No, there are no standard c or c++ functions to check whether an integer is a perfect square or a perfect cube.

If you want it to be fast and avoid using the float/double routines mentioned in most of the answers, then code a binary search using only integers. If you can find an n with n^2 < m < (n+1)^2, then m is not a perfect square. If m is a perfect square, then you'll find an n with n^2=m. The problem is discussed here

Solution 4

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.

Solution 5

Try this:

#include<math.h>
int isperfect(long n)
{
    double xp=sqrt((double)n);
    if(n==(xp*xp))
        return 1;
    else
        return 0;
}
Share:
44,624
d3vdpro
Author by

d3vdpro

Passionate and ambitious.

Updated on February 12, 2021

Comments

  • d3vdpro
    d3vdpro about 3 years

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