最大公约数GCD 也叫做Greatest Common Factor (最大公因数).
以下是Java code,说成C++也没差。
from Introduction to Java Programming and stackoverflow:
1 计算 GCD
方法 1
public static int gcd(int n1, int n2) {
int gcd = 1; // Initial gcd is 1
int k = 2; // Possible gcd
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k; // Update gcd
k++;
}
return gcd; // Return gcd
}
方法 2
public static int gcd(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
方法 3
public static int gcd(int a, int b)
{
/* additional iteration if (a < b) */
for (int t = 0; (t = b) != 0; a = t)
b = a % b;
return a;
}
2 计算 LCM
方法 1
public static int lcm(int a, int b)
{
int num1, num2;
if (a > b)
{
num1 = a;
num2 = b;
}
else
{
num1 = b;
num2 = a;
}
for (int i = 1; i < num2; i++)
{
if ((num1 * i) % num2 == 0)
{
return i * num1;
}
}
return num1 * num2;
}
方法 2
public static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}