Tuesday, 25 February 2014

2 L.C.N and H.C.F

//Write a c program to find out L.C.M. of two numbers.
Definition of LCM (Least common multiple):
LCM of two integers is a smallest positive integer which is multiple of both integers that it is divisible by the both of the numbers.
For example: LCM of two integers 2 and 5 is 10 since 10 is the smallest positive numbers which is divisible by both 2 and 5.
LCM program in c with two numbers :
#include<stdio.h>
int main(){
  int n1,n2,x,y;
  printf("\nEnter two numbers:");
  scanf("%d %d",&n1,&n2);
  x=n1,y=n2;
  while(n1!=n2){
      if(n1>n2)
           n1=n1-n2;
      else
      n2=n2-n1;
  }
  printf("L.C.M=%d",x*y/n1);
  return 0;
}
//Find HCF of two number using c program
HCF (Highest common factor)  program with two numbers in c
#include<stdio.h>
int main(){
int n1,n2;
printf("\nEnter two numbers:");
scanf("%d %d",&n1,&n2);
while(n1!=n2){
if(n1>=n2-1)
n1=n1-n2;
else
n2=n2-n1;
}
printf("\nGCD=%d",n1);
return 0;
}
HCF  program with multiple numbers in c 
#include<stdio.h>
int main(){
    int x,y=-1;
    printf("Insert numbers. To exit insert zero: ");

    while(1){
         scanf("%d",&x);
         if(x<1)
             break;
         else if(y==-1)
             y=x;
         else if (x<y)
             y=gcd(x,y);
         else
             y=gcd(y,x);
    }
    printf("GCD is %d",y);

    return 0;
}
int gcd(int x,int y){
    int i;
    for(i=x;i>=1;i--){
         if(x%i==0&&y%i==0){
             break;
         }
    }
    return i;
}

//Find g.c.d of two number using c program
Write a c program for finding gcd (greatest common divisor) of two given numbers
#include<stdio.h>

int main(){
    int x,y,m,i;
    printf("Insert any two number: ");
    scanf("%d%d",&x,&y);
    if(x>y)
         m=y;
    else
         m=x;
    for(i=m;i>=1;i--){
         if(x%i==0&&y%i==0){
             printf("\nHCF of two number is : %d",i) ;
             break;
         }
    }
    return 0;
}

No comments:

Post a Comment