how to find lcm of two numbers java

www.laut‮‬turi.com
how to find lcm of two numbers java

To find the least common multiple (LCM) of two numbers in Java, you can use a loop to find the multiples of each number and check if they are common to both numbers.

Here's an example of how to find the LCM of two numbers in Java:

int num1 = 15;
int num2 = 20;
int lcm = 1;

for (int i = 1; i <= num1 * num2; i++) {
  if (i % num1 == 0 && i % num2 == 0) {
    lcm = i;
    break;
  }
}

System.out.println("The LCM of " + num1 + " and " + num2 + " is " + lcm);

In the above example, a loop is used to iterate over the integers from 1 to the product of num1 and num2. For each integer, the loop checks if it is a multiple of both num1 and num2 using the modulo operator (%). If it is, the integer is stored in the lcm variable and the loop is exited.

Keep in mind that this example only finds the LCM of two numbers. To find the LCM of more than two numbers, you can use a similar approach or use the lcm() method of the java.math.BigInteger class.

For example:

import java.math.BigInteger;

int num1 = 15;
int num2 = 20;

BigInteger bigNum1 = BigInteger.valueOf(num1);
BigInteger bigNum2 = BigInteger.valueOf(num2);
BigInteger lcm = bigNum1.lcm(bigNum2);

System.out.println("The LCM of " + num1 + " and " + num2 + " is " + lcm);

In this example, the valueOf() method is used to convert the int values to BigInteger objects. The lcm() method is then used to calculate the LCM of the two numbers. The result is stored in the lcm variable and printed to the console.

Created Time:2017-11-01 20:42:51  Author:lautturi