Easy Tutorial
❮ C Return Pointer From Functions C Function Memmove ❯

C Exercise Example 16 - Greatest Common Divisor and Least Common Multiple

C Language Classic 100 Examples

Question: Input two positive integers m and n, and find their greatest common divisor and least common multiple.

Program Analysis:

(1) The least common multiple = the product of the two input numbers divided by their greatest common divisor. The key is to find the greatest common divisor;

(2) The greatest common divisor is found using the Euclidean algorithm (also known as the辗转相除法).

1) Proof: Let c be the greatest common divisor of a and b, denoted as c = gcd(a, b), where a >= b,

2) Algorithm description:

Step 1: Divide a by b, let r be the remainder (0 ≤ r < b). Step 2: Swap: Set a ← b, b ← r, and return to Step 1.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
int main()
{
    int a,b,t,r,n;
    printf("Please enter two numbers:\n");
    scanf("%d %d",&a,&b);
    if(a&lt;b)
    {t=b;b=a;a=t;}
    r=a%b;
    n=a*b;
    while(r!=0)
    {
        a=b;
        b=r;
        r=a%b;
    }
    printf("The greatest common divisor of these two numbers is %d, and the least common multiple is %d\n",b,n/b);

    return 0;
}

The above example output is:

Please enter two numbers:
12 26
The greatest common divisor of these two numbers is 2, and the least common multiple is 156

C Language Classic 100 Examples

❮ C Return Pointer From Functions C Function Memmove ❯