I am not understanding how the following formular works
http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm
Actually what I did (for my programming homework was loop through the max of 2 numbers until I get 1 that divides both given numbers without a remainder). Bruteforce, so not ideal. So I want to understand more about this formular instead of just using it.
public static int gcd(int a, int b) {
/**
* Get max of both numbers
* Loop down max number and test if its divisible by both numbers
* if yes, thats the answer, else continue
* if no answer, return 0
*/
int max = Math.max(a, b);
for (int i = max; i > 0; i--) {
if (a % i == 0 && b % i ==0) {
return i;
}
}
return 0;
}
a % i
takes the remainder after dividinga
byi
.) $\endgroup$ – J. M. isn't a mathematician Aug 23 '11 at 6:11