Monday, January 5, 2015

Lcm and Gcd and Hcf Recursion Program in C



Find LCM of a Number using Recursion
 
#include 
# include  
int lcm(int, int);
int main()
{
    int a, b, result;
    int prime[100];
    clrscr();
    printf("Enter two numbers: ");
    scanf("%d%d", &a, &b);
    result = lcm(a, b);
    printf("The LCM of %d and %d is %d\n", a, b, result);
    return 0;
}
 int lcm(int a, int b)
{ 
    static int common = 1;
 
    if (common % a == 0 && common % b == 0)
    {
        return common;
    }
    common++;
    lcm(a, b);
    return common;
getch();
}
 
Output
 
Enter two numbers: 456
12
The LCM of 456 and 12 is 456
 
Enter two numbers: 45 75
The LCM of 45 and 75 is 225
 
Find GCD of given Numbers using Recursion
 
#include 
#include 
int gcd(int, int);
int main()
{
    int a, b, result;
    clrscr();
    printf("Enter the two numbers to find their GCD: ");
    scanf("%d%d", &a, &b);
    result = gcd(a, b);
    printf("The GCD of %d and %d is %d.\n", a, b, result);
}
int gcd(int a, int b)
{
    while (a != b)
    {
        if (a > b)
        {
            return gcd(a - b, b);
        }
        else
        {
            return gcd(a, b - a);
        }
    }
    return a;
}
getch();
}

Output
 
Enter the two numbers to find their GCD: 100 70
The GCD of 100 and 70 is 10.
 
Find HCF of a given Number without using Recursion
 
#include 
#include 
int hcf(int, int);
int main()
{
    int a, b, result;
    printf("Enter the two numbers to find their HCF: ");
    scanf("%d%d", &a, &b);
    result = hcf(a, b);
    printf("The HCF of %d and %d is %d.\n", a, b, result);
    return 0;
}
int hcf(int a, int b)
{
    while (a != b)
    {
        if (a > b)
        {
            a = a - b;
        }
        else
        {
            b = b - a;
        }
    }
    return a;
}
 
Output
 
Enter the two numbers to find their HCF: 24 36
The HCF of 24 and 36 is 12.

No comments:

Post a Comment