I can not figure out what kind of mathematical function this code solve. Can someone explain to me?
int m = 12;
int n = 81;
while (m != n)
{
if (m > n)
m -= n;
else
n -= m;
}
System.out.println("m = " + m);
/* 12 != 81: true, 12 > 81: false, n = 81 - 12 = 69
12 != 69: true, 12 > 69: false, n = 69 - 12 = 57
12 != 57: true, 12 > 57: false, n = 57 - 12 = 45
12 != 45: true, 12 > 45: false, n = 45 - 12 = 33
12 != 33: true, 12 > 33: false, n = 33 - 12 = 21
12 != 21: true, 12 > 21: false, n = 21 - 12 = 9
12 != 9: true,12 > 9: true, m = 12 - 9 = 3
3 != 9: true, 3 > 9: false, n = 9 - 3 = 6
3 != 6: true, 3 > 6: false, n = 6 - 3 = 3
3 != 3: false
m = 3 */
This is an older algorithm called the Euclidean algorithm to find the greatest common divisor (GCD) of the two numbers.
The Euclidean algorithm is a more efficient way for finding the GCD of two numbers. This code works by taking two integers, m
and n
then it repeatedly subtracts the smaller of the two numbers from the larger one until they become equal. The common value is the greatest common divisor of the original two numbers as per rule.
In the code m
starts at 12 and n
starts at 81. You repeatedly subtract the smaller number from the larger one until they become equal. At the end m
becomes 3 and n
becomes 3. Because m
is now equal to n
, the loop ends (thy while
loop condition m!=n
). The value of m
or n
is the greatest common divisor of the original two numbers, which is 3.