-4

I would like to square/cube root but also 4,5,etc. how would I do this?
I can do square

public static boolean isSquareNumber(int n) {
    int a  = (int) Math.sqrt(n);
    if(Math.pow(a, 2) == n) {
        return true;
    } else {
        return false;
    }
}

How would I do this for other powers?

2 Answers2

1

The hole issue is about how you are addressing the problem(IMHO)

a number x can be rooted to a base n if:

the x^(1/n) is an integer, where n > 0

therefore the approach could be:

public static void main(final String[] args) {
    for (int i = 1; i <= 10; i++) {
        System.out.println(" has " + i + " exactly a root base2(square)? " + isRootInteger(i, 2));
        System.out.println(" has " + i + " exactly a root base3(cubic)? " + isRootInteger(i, 3));
    }

}

public static boolean isRootInteger(int number, int root) {
    double dResult = Math.pow(number, 1.0 / root);

    if ((dResult == Math.floor(dResult)) && !Double.isInfinite(dResult)) {
        return true;
    }
    return false;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
-1

If you take the power and find the inverse of it, 1/power it gives you the root of that power.

public static boolean isPowerNumber(int n, double power) {
    int a = (int) Math.pow(n, (1/power));
    if(Math.pow(a,power) == n) {
        return true;
    } else {
        return false;
    }
}

Here is the code that you will need.