I had faced a interview question to find the gdc(greatest common divisor) for an integer array of element in optimised way :
Sample case :
a[] = { 10,20,19,15,13}
Result = 1
sample case :
a[]={9,21,12,15,27}
Result : 3
I have submitted following result during the interview. But he asked to optimise the same. Solution which I proposesd:
package threeDpalm;
import java.util.Arrays;
public class GCF {
public static void main(String ag[]){
GCF gcf = new GCF();
gcf.check();
}
void check(){
int[] input = {40,52};
int [] original =input.clone();
boolean flag = true;
int min_araay = Integer.MAX_VALUE;
int countResult=0;
int count=0;
int k1=0;
while (flag){
countResult=0;
count=0;
//finding the minimum no which is greater than zero
for (int j : input){
if(j<min_araay && j!=0){
min_araay = j;
}
}
// Applying Elucid algo...diving the lowesst elemt with other to remove the multiple of lowest
for (int k=0;k<input.length; k++){
input[k]= input [k]%min_araay;
// if all the element are Zero, then it is the GCD..counting the Zero...
if(input[k]==0){
count++;
//if count = length ..breaking the loop
if(count == input.length){
flag =false;
}
}
}
}
//checking the result by diving each elemt of the array. cheking for all the no less than that
for ( k1= min_araay;k1>0;k1--){
countResult=0;
for (int j : original){
if (j%k1==0){
countResult++;}}
if (countResult==original.length){
System.out.println(k1);
return;
}
}
}
}
Can some one please help me with better solution
input
value and your code doesn't work in at least some special cases, I'm going to assume you did not test this for any scenarios besides your single hard-coded case. As such, I'm voting to close this question as containing broken code. – nhgrif Jun 20 at 11:21