This blog is under construction

Monday 8 July 2013

C program to calculate Least Common Multiple(LCM)

Write a C program to calculate Least Common Multiple(LCM).


  #include <stdio.h>

  int main() {
        int x, y, lcm, val, i = 2;

        /* get the input numbers from the user */
        printf("Number 1:");
        scanf("%d", &x);
        printf("Number 2:");
        scanf("%d", &y);

        /* take the smallest of x and y to manipulate lcm */
        if (x < y) {
                val = x;
        } else {
                val = y;
        }

        /* if the smallest is 0 or 1, then lcm is 0 or 1 correspondingly */
        if (val <= 1) {
                printf("LCM of %d and %d is %d\n", x, y, val);
                return 0;
        }

        /* calculate lcm */
        while (i <= val) {
                if ((x % i == 0) && (y % i == 0)) {
                        break;
                }
                i++;
        }
        /* no lcm found - set lcm as 1  */
        if ((i- 1) == val) {
                lcm = 1;
        } else {
                lcm = i;
        }

        /* print the results */
        printf("LCM of %d and %d is %d\n", x, y, lcm);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Number 1:55
  Number 2:100
  LCM of 55 and 100 is 5





See Also:

No comments:

Post a Comment