What about this, you iterate over the array and check that the square of the square root is the same as the original number. If so, you add it to a list that you convert to an array once you are done.
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9,10 };
List<Integer> resultList = new ArrayList<>();
for (int number: numbers) {
int sqrRoot = (int) Math.round(Math.sqrt(number));
if (sqrRoot * sqrRoot == number) {
resultList.add(number);
}
}
or if you cannot use a List
(see comment of author of the original question, below)…
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9,10 };
int[] initResult = new int[numbers.length];
int numSquares = 0;
for (int i = 0; i < numbers.length; i++) {
int sqrRoot = (int) Math.round(Math.sqrt(numbers[i]));
if (sqrRoot * sqrRoot == numbers[i]) {
initResult[numSquares] = numbers[i];
numSquares++;
}
}
int[] result = new int[numSquares];
for (int i = 0; i < numSquares; i++) {
result[i] = initResult[i];
}
The reason I calculate the square root as follows (int) Math.round(Math.sqrt(numbers[i]))
is to prevent floating point arithmetic issues. This way, the square root of the integer 4 will always be an integer with value 2.
3
solved How to filter squares in an array [closed]