Saturday, 17 January 2015

HCF and LCM of two number

Find the HCF and LCM of two number.

public class HCF {
 static    int absFun(int num){
        return(num>0?num:(-num));
    }
    int calculateHCF(int x,int y){
        if((x!=0)&&(y!=0))
        return (x>y)?(calculateHCF(y,x%y)):(calculateHCF(x,y%x));
        return (x>y?x:y);
        }   
    int getLCM(int x,int y,int i){
        return( ( ((x*i)%x)+((x*i)%y)==0 )?(x*i):getLCM(x, y, i+1));
    }
    int calculateLCM(int x,int y){
        int i=1;
        return(x>y?getLCM(x,y,i):getLCM(y,x,i));
    }
public static void main(String[] args) {
    int x=15;
    int y=5;
    x=absFun(x);
    y=absFun(y);
    HCF obj=new HCF();
    int hcf=obj.calculateHCF(x, y);
    System.out.println("HCF:"+hcf);
    System.out.println("+++++++++++++++++");
    System.out.println("LCM="+obj.calculateLCM(x,y));
  }
}

=======================================
Output:
HCF:5
+++++++++++++++++
LCM=15




No comments:

Post a Comment