21xrx.com
2024-11-25 22:21:11 Monday
登录
文章检索 我的文章 写文章
Code Example: Java Calculate Least Common Multiple
2023-06-16 19:33:57 深夜i     --     --

Code Example: Java Calculate Least Common Multiple

In Java, the least common multiple (LCM) of two or more positive integers can be calculated using the following formula:

LCM(a,b) = (a*b) / GCD(a,b)

where GCD is the greatest common divisor. To calculate the GCD, we can use the Euclidean algorithm.

Here is an example code snippet that demonstrates how to calculate the LCM of two integers in Java:


public static int calculateLCM(int a, int b) {

  int gcd = calculateGCD(a,b);

  return (a*b) / gcd;

}

public static int calculateGCD(int a, int b) {

  if (b == 0)

    return a;

   else {

    return calculateGCD(b, a%b);

  }

}

Let's say we want to find the LCM of 12 and 18. We can call the `calculateLCM` method and pass in the two integers as arguments:


int lcm = calculateLCM(12, 18);

System.out.println("LCM of 12 and 18 is " + lcm); // Output: LCM of 12 and 18 is 36

In this case, the LCM of 12 and 18 is 36.

These are three keywords related to Java calculating the least common multiple: Java, gcd, lcm.

Overall, calculating the least common multiple in Java involves finding the greatest common divisor using the Euclidean algorithm and then applying the LCM formula. With the example code provided above, you can easily calculate the LCM of any two positive integers in Java.

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复