Wednesday 24 January 2018

GCD and LCM of n numbers stored in an array.

#include<stdio.h>
#include<stdlib.h>
int gcd(int a,int b)
{
if(a==0)
return b;
else
return gcd(b%a,a);
}
int lcm(int a,int b)
{
return a*(b/gcd(a,b));
}
int main()
{
int i,n;
/*To calculate GCD of n elementst we have to initailize starting variable with 0 (no with 1 )*/
int resgcd=0;
/*To calculate GCD of n elementst we have to initailize starting variable with 1 (no with 0 )*/
int reslcm=1;
printf("Enter the size of array:");
scanf("%d",&n);
int *ar=(int *)malloc(n*sizeof(int));
printf("\nEnter the elements of array:\n");
for(i=0;i<n;i++)
scanf("%d",&ar[i]);
for(i=0;i<n;i++)
resgcd=gcd(resgcd,ar[i]);
for(i=0;i<n;i++)
reslcm=lcm(reslcm,ar[i]);
printf("GCD : %d",resgcd);
printf("\nLCM : %d",reslcm);
return 0;
}

No comments:

Post a Comment