-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?

ThorinDev
  • 35
  • 1
  • 7
  • 2
    The `n`th root of `x` can be given by `Math.pow(x, 1.0/n)`. – khelwood Feb 17 '17 at 14:42
  • 3
    It's a math problem, not a java one, vote to close, not the appropriate place – azro Feb 17 '17 at 14:43
  • This is more of a math question than java. You can do Math.pow(a, 1.0/p) where p is the power you want and of type double, e.g. 2, 3, ...etc – Multithreader Feb 17 '17 at 14:43
  • @azro That may be true, but I wanted to create a java program to solve them, so I thought it went in java. – ThorinDev Feb 17 '17 at 14:45
  • 4
    Possible duplicate of [Calculating nth root in Java using power method](http://stackoverflow.com/questions/32553108/calculating-nth-root-in-java-using-power-method) – Akceptor Feb 17 '17 at 14:48
  • Very useful link, @Akceptor, certainly relevant. I don’t think this is an exact duplicate, though. – Ole V.V. Feb 17 '17 at 15:13

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 ツ
  • 45,713
  • 17
  • 64
  • 91
-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.

ThorinDev
  • 35
  • 1
  • 7