I wrote a function which returns true
only if a given array contains at least one integer that can divide all the other integers. Otherwise returns false
.
Here's what I've tried:
public static boolean check(int[] arr) {
int n = arr.length;
boolean res = false;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(arr[i]%arr[j]!=0 && arr[j]%arr[i]!=0) break;
if(j == n-1) res = true;
}
}
return res;
}
public static void main(String []args){
int[] arr = {4,2,6,8};
System.out.println(check(arr)); // -> true
int[] arr2 = {4,3,6,8};
System.out.println(check(arr2)); // -> false
}
Seems like my code provides the correct output, but I want to know a better approach without having to use nested for loops.