1. 程式人生 > >計算最大公約數 GCD (Greatest Common Divisor)和最小公倍數 LCM (Least Common Multiple)

計算最大公約數 GCD (Greatest Common Divisor)和最小公倍數 LCM (Least Common Multiple)

文章目錄


最大公約數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;
}