How To Ideas | How To Articles | How To Tutorials


0

How to find Least Common Multiple ( LCM ) of two numbers in C


Least Common Multiple (LCM) of two numbers is the smallest positive integer which is also a multiple of both the numbers. If any of the two numbers is 0, LCM of those two numbers will be 0. You can find more about LCM of two numbers on Wikipedia.

Algorithm:

  1. Let a and b be the two numbers whose LCM you want to find.
  2. Let temp be any temporary number, initially set to the bigger number among a and b.
  3. Check whether temp is perfectly divisible by both a and b or not.
  4. If it is, then temp is the LCM of a and b, otherwise move to step 5.
  5. Increment the value of temp and move to step 3.

Instructions:

  1. Use only the following header file in C program.

    #include <stdio.h>

  2. In main, ask the user to input two numbers whose LCM he/she wants to find.
    int a,b, temp;
    printf("Enter two numbers whose LCM you want to find : ");
    scanf("%d%d", &a, &b);
  3. Find the LCM of these two numbers a and b using the user defined function findLCM which will return LCM of these two number and print its value.
    temp = findLCM(a, b);
    printf("LCM of %d and %d is %d", a, b, temp);
  4. In findLCM function, define a temporary variable lcm and assign it value of the bigger number among a and b (i.e. if a > b then lcm = a, otherwise lcm = b). No using a while loop which will run untill lcm becomes perfectly divisible by both a and b, and increment the value of lcm in this loop. And finally return the value of variable lcm.
    int findLCM(int a, int b)
    {
        int lcm = a > b ? a : b;
        while(lcm % a != 0 || lcm % b != 0)
        {
            lcm++;
        }
        return lcm;
    }

Here are some screenshots of sample programs.

LCM of two numbers using C

LCM of two numbers using C

LCM of two numbers using C

LCM of two numbers using C

You can download the sample code from here.

Incoming search terms:

  • code to find lcm of two numbers (1)
  • program LCM in C (1)
Filed in: C Tags: , , , , , , , , ,

Leave a Reply

Submit Comment



© 7083 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.