Write a C Program to Compute the LCM and HCF of Two Numbers by using While Statement

Engg.... | 01:32 | | Best Blogger Tips
LCM and HCF

HCF:
  • HCF Stands For Higest Common Factor.
  • HCF is also Known as GCD (Greatest Common Divisor).
  • HCF of Two Number is defined as the Largest Number that Divides Both Numbers Completely with Remainder Zero.
LCM:
  • LCM Stands For Lowest Common Multiple.
  • LCM of two Numbers Defined as the Smallest Number that is Multiple of both Numbers. 
Statement of C Program: Find The LCM and HCF of Two Numbers :

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

void main()
{
int num1 , num2 , lcm , gcd , remainder , numerator , denominator ;
clrscr();

printf( "Enter two numbers\n");
scanf(" %d%d " , &num1 , &num2 );
if (num1 > num2)
{
numerator=num1;
denominator=num2;
}
else
{
numerator = num2 ;
denominator = num1 ;
}

remainder = num1 % num2;
while ( remainder != 0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
gcd = denominator;
lcm = (num1 * num2 ) / gcd;

printf("GCD of %d and %d =%d\n" , num1, num2, gcd);
printf(" LCM of %d and %d= %d\n" , num1, num2, lcm);
getch();
}

Output:
 Enter two numbers
 5
 15
 GCD of 5 and 15 = 5
 LCM of 5 and 15 = 15


Please Share it! :)
Do you like this Story?

Get Free Email Updates Daily!

Follow us!

2 comments:

  1. Chosen participants will receive financial support to attend WLA conferences,
    dissertation topics coming up

    ReplyDelete
  2. hey dear there is a bug in the program :
    just type num1 a smaller value then num 2 ...
    the program will not generate desired output.. here is the simple modification :


    int main()
    {
    int num1 , num2 , lcm , gcd , remainder , numerator , denominator;

    printf( "Enter two numbers\n");
    scanf("%d%d" , &num1 , &num2 );
    if (num1 > num2)
    {
    numerator=num1;
    denominator=num2;
    remainder = num1 % num2;//now at correct place :)
    }
    else
    {
    numerator=num2;
    denominator=num1;
    remainder = num2 % num1;// this was missing :)
    }
    while ( remainder != 0)
    {
    numerator = denominator;
    denominator = remainder;
    remainder = numerator % denominator;
    }
    gcd = denominator;
    lcm = (num1 * num2 ) / gcd;

    printf("GCD of %d and %d =%d\n" , num1, num2, gcd);
    printf(" LCM of %d and %d= %d\n" , num1, num2, lcm);
    getch();
    return 0;
    }

    ReplyDelete