AMCAT Coding Questions asked in Programming Section - LCM of Two Numbers

Program to find LCM


/**
 * C program to find LCM of any two numbers
 */
#include <stdio.h>
int main()
{
    int i, num1, num2, max, lcm=1;
    /*
     * Reads two numbers from user
     */
    printf("Enter any two numbers to find LCM: ");
    scanf("%d %d", &num1, &num2);
    max = (num1>num2) ? num1 : num2;
    i = max;
     
    //Loop runs forever
    while(1)
    {
        /* If i is a multiple of both numbers */
        if(i%num1==0 && i%num2==0)
        {
            lcm = i;
            break;
        }
        i += max;
    }
    printf("\nLCM of %d and %d = %d\n", num1, num2, lcm);
    return 0;
}




Output
Enter any two numbers to find LCM: 12
30

LCM of 12 and 30 = 60

No comments:

Post a Comment