Wednesday, 16 May 2012

Write a C program to find out hcf and lcm of n numbers.

Underlying concept to demonstrate: dynamic allocation of a 1-d array.

#include<stdio.h>
#include<stdlib.h>
int Hcf(int n1,int n2);
int Lcm(int n1,int n2);

int main()
{
    int x,y,hcf,lcm,i;
    unsigned n;
    printf("\n How many numbers you want to enter ?");
    scanf("%u",&n);
    int *p;
    p=(int *)malloc(n*sizeof(int));
    printf("\n Enter first no.:");
    scanf("%d",&x);
    printf("\n Enter next no.:");
    scanf("%d",&y);   
    hcf=Hcf(x,y);
    lcm=Lcm(x,y);
    i=2;
    while(i<n)
    {
        printf("\n Enter next no.:");
        i++;   
        scanf("%d",&x);
        hcf=Hcf(hcf,x);   
        lcm=Lcm(lcm,x);
       
    }
    printf("\n Hcf and Lcm of the nos. you have entered is %d and %d respectively",hcf,lcm);
    return 0;
}



//fn to calculate hcf of two nos.

int Hcf(int n,int m)
{
    int i,min,max,remain=1,divisor,dividend,hcf;
    if(n>m)
    {
        max=n;   
        min=m;
    }
    else
    {
        max=m;
        min=n;
    }
   
    divisor=min;
    dividend=max;
    while(remain>0)
    {
        remain=dividend%divisor;
        dividend=divisor;
        divisor=remain;
    }
    if(remain==0)
    {
        hcf=dividend;
        return hcf;
    }
   
}


int Lcm(int n,int m)
{
    int hcf;
    hcf=Hcf(n,m);
    int lcm;
    lcm=(n*m)/hcf;
    return lcm;
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top