mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Added function and fixed bug in PerfectCube.java (#3655)
* Added another function to PerfectCube.java Added another function to PerfectCube.java and fixed a testing mistake in line number 9 * Created PerfectCubeTest.java Created PerfectCubeTest.java * fixed PerfectCubeTest.java * Fixed bug in PerfectCube.java Fixed bug in PerfectCube.java in isPerfectCube() function for negative numbers. Now It gives the correct output for perfect negative numbers. * removed main() in PerfectCube.java
This commit is contained in:

committed by
GitHub

parent
5ab1b6c319
commit
957f633c93
@ -5,15 +5,6 @@ package com.thealgorithms.maths;
|
||||
*/
|
||||
public class PerfectCube {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert !isPerfectCube(-1);
|
||||
assert isPerfectCube(0);
|
||||
assert isPerfectCube(1);
|
||||
assert !isPerfectCube(4);
|
||||
assert isPerfectCube(8);
|
||||
assert isPerfectCube(27);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a number is perfect cube or not
|
||||
*
|
||||
@ -22,7 +13,20 @@ public class PerfectCube {
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isPerfectCube(int number) {
|
||||
number = Math.abs(number); // converting negative number to positive number
|
||||
int a = (int) Math.pow(number, 1.0 / 3);
|
||||
return a * a * a == number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a number is perfect cube or not by using Math.cbrt function
|
||||
*
|
||||
* @param number number to check
|
||||
* @return {@code true} if {@code number} is perfect cube, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isPerfectCubeMathCbrt(int number) {
|
||||
double cubeRoot = Math.cbrt(number);
|
||||
return cubeRoot == (int) cubeRoot;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user