Question

I have used Euclid's method to find the L.C.M for two numbers.

l.c.m=a*b/(gcd(a,b))

How can I do this without using this algorithm? I have an idea of first getting all factors of these two numbers and storing them in array. Then take 1 element from array 1 and search for it in array2, if it present there then remove it from there and make the result multiply by that num.

Is this OK?

Was it helpful?

Solution

Almost. What's the LCM of 4 and 8? Obviously 8 (23), but in your method you'd find 2. You need to keep track not just of all factors, but also how often they appear.

OTHER TIPS

I believe the algorithm you suggest is a method using a table, check to see if it works for you.

LCM(Least Common Multiple) is always greater than or equal to the larger of the two numbers. So we will first check that the larger number itself a LCM of two numbers by checking that the larger number is divisible by the smaller one , if yes we found the LCM & If no then we will increment the larger number by 1 and check again.

package com.company;
import java.util.Scanner;

public class Main {

public static void main(String args[]) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter the first Number : ");
    int number1 = scan.nextInt();
    System.out.print("Enter the second number : ");
    int number2 =scan.nextInt();

    int multiple;

    if(number1 >= number2) {
        multiple = number1;
    } else {
        multiple = number2;
    }

    Boolean loopContinue = true;

    while(loopContinue) {
        if(multiple % number1 == 0 && multiple % number2 == 0) {
            System.out.println("LCM of Two Numbers is " + multiple);
            loopContinue = false;
        }
        multiple++;
    }
  }
}

You can get LCM of two number by getting GCD at first. Here is the solution for the above.

package com.practice.competitive.maths;

import java.util.Scanner;

public class LCMandGCD {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int testCases = scanner.nextInt();
            while (testCases-- > 0) {
                long number1 = scanner.nextInt();
                long number2 = scanner.nextInt();
                long gcd = computeGCD(number1, number2);
                long lcm = computeLCM(number1, number2, gcd);
                System.out.println(lcm + " " + gcd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static long computeGCD(long number1, long number2) {
        while (number1 != number2) {
            if (number1 > number2)
                number1 -= number2;
            else
                number2 -= number1;
        }   
        return number2;
    }

    private static long computeLCM(long number1, long number2, long gcd) {
        return (number1*number2)/gcd;
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top