This was another coding challenge I came across while practising online. Little bit tricky, however, I found a solution (I say 'a' solution because there can be alternative ways to do the same) for it.
So, what are we suppose to do here?
- A method accepts two integer parameters and we need to find the highest divisible integer by which both the numbers could be divided without a remainder.
- If either one of the given number is less than 10 then the method should return -10 indicating invalid input.
here is my solution and I hope it's helpful.
public class GreatestCommonDivisor {
public static int getGreatestCommonDivisor(int first, int second){
int greatestCommonDivisor = -1;
if(first >= 10 && second >= 10){
int smallerNumber = first < second ? first : second;
for(int i = smallerNumber ; i >= 1 ; i--){
if( (first % i == 0) && (second % i == 0)){
greatestCommonDivisor = i;
break;
}else{
continue;
}
}
}
return greatestCommonDivisor;
}
}
No comments:
Post a Comment