Pages - Menu

Monday 8 October 2012

The least common multiple in C


Least common multiple of two integers



The least common multiple, also called the lowest common multiple or smallest common multiple of two integers a and b is the smallest positive integer that is a multiple of both a and b. (wikipedia)

In order to compute the least common multiple of the two numbers, a and b, I will use this formula:
lcm = a*b/gcd, gcd being the greatest common divisor of a and b.

Read this article to see the function used below that I implemented for finding the gcd of two integers.
/*
 * Description:
 *  Finds the least common multiple
 * Parameters:
 *  a - the first number
 *  b - the second number
 * Returns:
 *  lcm - the least common multiple of a and b
 */
int LCM(int a, int b)
{
    int lcm = 0;
 if(a < 0)
 {
  a = -a;
 }
 if(b < 0)
 {
  b = -b;
 }
 lcm = a*b/GCD(a,b);
    return lcm;
}

Example:

#include<stdio.h>
#include<conio.h>

int LCM(int a, int b);

int main(void)
{
    int a = 0, b = 0, lcm = 0;
    printf("\n Enter the first number: ");
    scanf("%d",&a);
    printf(" Enter the second number: ");
    scanf("%d",&b);
    lcm = LCM(a,b);
    printf("\n\tThe least common multiple is: %d",lcm);
    getch();
    return 0;
}
Output:   




Least common multiple of an array of integers


/*
 * Description:
 *  Finds the least common multiple of an array of integers
 * Parameters:
 *  a     - the array
 *  first - the index of the leftmost elements of the array
 *  last  - the index of the rightmost element of the array
 * Returns:
 *  lcm - the least common multiple
 */
int ArrayLCM(int *a, int first, int last)
{
    int i = 0, lcm = a[first];
    for(i=first+1; i<=last; i++)
    {
        lcm = LCM(lcm,a[i]);
    }
    return lcm;
}
Example:
#include<stdio.h>
#include<conio.h>

int ArrayLCM(int *a, int first, int last);

int main(void)
{
    int a[20], n = 0, i = 0, lcm = 0;
    printf("\n Enter the number of elements of the array: ");
    scanf("%d",&n);
    printf(" Enter the elements of the array:\n");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    lcm = ArrayLCM(a,0,n-1);
    printf("\n\tThe greatest common divisor is: %d",lcm);
    getch();
    return 0;
}
Output:   

No comments:

Post a Comment