I want to check if an array Is235. Is235 is an array that has an integer divisible by 2, another integer divisible by 3 and a third integer divisible by 5. The other integers in the array that aren’t divisible by either of 2, 3, or 5 when added to the integers divisible by 2, 3 and 5 should be equal to the total number of elements in the array. Return 1 if the array Is235, else return 0. Please note that array cannot contain negative integers or zero. I want to approach this in a brute force manner only, thanks for your help in advance. My wrong attempt –
public class Array { public static void main(String[] args) { int[] arr = {2, 3, 5, 7, 11}; System.out.println(is235Array(arr)); } public static int is235Array(int[] a) { int n = a.length; int countOne = 0; int countTwo = 0; for (int i = 0; i < a.length; i++) { if (a[i] / 2 == 0 || a[i] / 3 == 0 || a[i] / 5 == 0) { countOne++; } } for (int j = 0; j < a.length; j++) { if (a[j] / 2 != 0 || a[j] / 3 != 0 || a[j] / 5 != 0) { countTwo++; } } if (countOne + countTwo != n) { return 0; } return 1; } }
My countOne and countTwo variables couldn’t count the integers as i taught it would.
Advertisement
Answer
Try this, I tested it and it works, you should use the remainder operator %
:
public class Array { public static void main(String[] args) { int[] arr = {2, 3, 5, 7, 11}; System.out.println(is235Array(arr)); } public static int is235Array(int[] a) { int countOne = 0; int countTwo = 0; for (int i : a) { if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0) { countOne++; }else{countTwo++;} } if (countOne + countTwo != a.length) { return 0; }else{return 1;} } }