w3resource

C Exercises: Determine the LCM of two numbers


45. LCM of Two Numbers

Write a program in C to find the LCM of any two numbers.

Visual Presentation:

Determine the LCM of two numbers

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.

void main()  
{  
    int i, n1, n2, max, lcm = 1;  // Declare variables to store input and results.

    printf("\n\n  LCM of two numbers:\n ");  // Print a message.
    printf("----------------------\n");  // Print a separator.

    printf("Input 1st number for LCM: ");  // Prompt the user for input.
    scanf("%d", &n1);  // Read the first number from the user.
    printf("Input 2nd number for LCM: ");  // Prompt the user for input.
    scanf("%d", &n2);  // Read the second number from the user.

    max = (n1 > n2) ? n1 : n2;  // Determine the larger of the two numbers.  

    // Loop to find the least common multiple (LCM).
    for (i = max; ; i += max)  
    {  
        if (i % n1 == 0 && i % n2 == 0)  
        {  
            lcm = i;  // Update the LCM whenever a common multiple is found.
            break;  // Exit the loop once LCM is found.
        }  
    }  

    // Print the result.
    printf("\nLCM of %d and %d = %d\n\n", n1, n2, lcm);  
}

Output:

  LCM of two numbers:                                                                                         
 ----------------------                                                                                       
Input 1st number for LCM: 15                                                                                  
Input 2nd number for LCM: 20                                                                                  
                                                                                                              
LCM of 15 and 20 = 60 

Flowchart:

Flowchart : Determine the LCM of two numbers using HCF.

For more Practice: Solve these Related Problems:

  • Write a C program to calculate the LCM of two numbers without using HCF by iterating through multiples.
  • Write a C program to determine the LCM of two numbers using a for loop and breaking when found.
  • Write a C program to compute the LCM of two numbers using dynamic programming to store intermediate multiples.
  • Write a C program to find the LCM of two numbers and then extend the solution to find the LCM of three numbers.

Go to:


PREV : LCM Using HCF.
NEXT : Binary to Decimal Using Math Function.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.