I'm trying to write a code which gets a array of ints and checks if the square root of the number is in the array, if yes it will print yes else it will print no. I can't figure out why my code returns no all the time.
For example if my input is : 1 4 0 2 16 3
My output will be : yes yes yes no yes no
This is my code:
import java.util.Arrays;
public class Assignment02Q04 {
public static void main(String[] args) {
int[] intlist = new int[args.length];
for (int i=0; i < args.length; i++) {
intlist[i] = Integer.parseInt(args[i]);
}
for (int number : intlist) {
int sqrt = (int)(Math.sqrt(number));
System.out.println(sqrt);
if (Arrays.asList(intlist).contains(sqrt)) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}
Consider using a collection from the start, instead of continuously converting, using Arrays.asList(). Also, check that the number has a natural square root by using floor on the square root and comparing it's power of 2 to the original number. Here is the code which returns the expected result yes yes yes no yes no: