Thursday, 16 February 2017

HCF and LCM Java Program

Q : Write a program to input two number and find out HCF and LCM ?

Solution : 


class lcm {
 void get(m1, m2) {

  int min, max, lcm, hcf, i, x;
  min = m1;
  max = m2;
  //calculate HCF
  for (i = min; i >= 1; i--) {
   if (min % i == 0 && max % i == 0) {
    hcf = i;
    break;
   }
  }
  //calculate LCM
  for (i = 1; i < max; i++) {
   x = max * i;
   if (x % min == 0) {
    lcm = x;
    break;
   }
  }
  System.out.println("L.C.M is " + lcm);
  System.out.println("H.C.M is " + hcm);
 }
}

No comments:

Post a Comment