Tuesday, May 8, 2012

LCM implementation in Java


public class Maths {
      public int lcm(int num1, int num2) {
            if (num1 == 0 || num2 == 0) {
                  return 0;
            }
            if (num1 < num2) {
                  num1 = num1 ^ num2;
                  num2 = num1 ^ num2;
                  num1 = num1 ^ num2;
            }
            int num = num1 % num2;
            if (num == 0) {
                  return num1;
            }

            for (int i = 2; i <= num; i++) {
                  if ((num1 * i) % num2 == 0) {
                        return i * num1;
                  }
            }
            return num1 * num2;
      }

      public static void main(String[] args) {
            int a = 24;
            int b = 16;

            Maths m = new Maths();
            int l = m.lcm(a, b);
            System.out.println("LCM is " + l);
      }
}

No comments:

Post a Comment