2017-02-17 61 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; 
} 
相關問題