java - Arrays.asList issue when computing square root of integer array elements -
i'm trying write code gets array of ints , checks if square root of number in array, if yes print yes else print no. can't figure out why code returns no time.
for illustration if input : 1 4 0 2 16 3
my output : yes yes yes no yes no
this code:
import java.util.arrays; public class assignment02q04 { public static void main(string[] args) { int[] intlist = new int[args.length]; (int i=0; < args.length; i++) { intlist[i] = integer.parseint(args[i]); } (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 collection start, instead of continuously converting, using arrays.aslist(). also, check number has natural square root using floor on square root , comparing it's powerfulness of 2 original number. here code returns expected result yes yes yes no yes no:
public static void main(string[] args) { list<integer> intlist = new arraylist<integer>(); (int = 0; < args.length; i++) { intlist.add(integer.parseint(args[i])); } (int number : intlist) { int sqrt = (int) (math.floor(math.sqrt(number))); if (sqrt * sqrt == number && intlist.contains(sqrt)) { system.out.print("yes "); } else { system.out.print("no "); } } }
java arrays list square-root
No comments:
Post a Comment