2017-02-17 86 views
-4

我想平方根/立方体根也可以4,5等等。我将如何做到这一点?
我可以做多Java看看一个数字是否可以是平方根/立方根

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

如何将我的其他权力这样做吗?

+2

''n'的第n个根可以由'Math.pow(x,1.0/n)'给出。 – khelwood

+3

这是一个数学问题,而不是一个Java,投票结束,而不是适当的地方 – azro

+0

这是一个比java更多的数学问题。你可以做Math.pow(a,1.0/p),其中p是你想要的权力和double类型的权力。 2,3,... etc – Multithreader

回答

-1

如果你掌握了权力并找到它的反例,那么它会给你权力的根源。

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

这是您需要的代码。

+3

'1/power'会给你任何int'power'> 1的值为零。 – khelwood

+0

将“power”从int改为double – Dolf

1

空穴问题是关于你如何解决这个问题(IMHO)

若干X可以植根于基Ñ如果:

的x ^(1/n的)是整数,其中n> 0

因此该方法可以是:

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