YouTip LogoYouTip

C Examples Lcm

C Programming Example - Find the Least Common Multiple of Two Numbers

User inputs two numbers and finds the least common multiple (LCM) of these two numbers.

Example - Using while and if

#include<stdio.h>
int main()
{
    int n1, n2, minMultiple;

    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);

    // Determine the larger of the two numbers and assign it to minMultiple
    minMultiple = (n1>n2) ? n1 : n2;

    // The condition is true
    while(1)
    {
        if(minMultiple%n1==0 && minMultiple%n2==0)
        {
            printf("The least common multiple of %d and %d is %d", n1, n2, minMultiple);
            break;
        }
        ++minMultiple;
    }

    return 0;
}

Result:

Enter two positive integers: 72 120
The least common multiple of 72 and 120 is 360

Example - Calculating via Greatest Common Divisor (GCD)

#include<stdio.h>
int main()
{
    int n1, n2, i, gcd, lcm;

    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);

    for(i=1; i<= n1 && i<= n2; ++i)
    {
        // Determine the greatest common divisor
        if(n1%i==0 && n2%i==0)
            gcd = i;
    }

    lcm = (n1*n2)/gcd;
    printf("The least common multiple of %d and %d is %d", n1, n2, lcm);

    return 0;
}

Result:

Enter two positive integers: 72 120
The least common multiple of 72 and 120 is 360

1 Note

#0 Jared

der***k_cui@163.com

Combined with the previous language example:

#include <stdio.h>
int gcd(int m, int n)
{ // Define function
    if(m % n == 0)
        return n;
    else
        return gcd(n, m%n); // Euclidean algorithm
}

void main()
{
    int a, b, t, lcm;
    printf("Please enter two numbers: ");
    scanf("%d%d", &a, &b);

    if(a < b)
    {
        t=a; a=b; b=t;
    } // Ensure a > b

    t = gcd(a, b); // Recursive call
    printf("The greatest common divisor of %d and %d is: %dn", a, b, t);

    lcm = (a * b)/ t; // Calculate the least common multiple using the greatest common divisor t
    printf("The least common multiple of %d and %d is: %d", a, b, lcm);
}

Result:

Please enter two numbers: 12 18
The greatest common divisor of 18 and 12 is: 6

Jared

der***k_cui@163.com 7 years ago (2019-06-28)

← C Examples Power NumberC Examples Factorial β†’