Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

GCD (Greatest Common Divisor ) Euclids way

GCD (Greatest Common Divisor ) Euclids way
public class GreatestCommonDivisor {

//using euclid's way of calculating GCD
static int greatestCommonDivisor(int a, int b) {
int gdivisor = 1, divider, dividend;
if (a < b) { // the one less is divisor the one greater is dividend
divider = a;
dividend = b;
}
else {
divider = b;
dividend = a;
}

if (dividend % divider == 0) { //its the GCD
return divider;
}
else { //proceed further
greatestCommonDivisor(divider, dividend % divider);
}
return gdivisor; //the GCD of the 2 numbers
}

public static void main(String args[]) {
System.out.println(greatestCommonDivisor(5, 144));
}
}
GCD (Greatest Common Divisor ) Euclids way

1 comment:

Search 24 Bytes

Loading...