Чтобы найти наименьшее общее кратное (НОК) двух чисел в Java, можно использовать несколько методов. Вот несколько подходов:
Метод 1: использование формулы НОК
Вы можете рассчитать НОК, используя формулу НОК(a, b) = (a * b) / НОД(a, b), где НОД представляет собой наибольший общий делитель.
public class LCMCalculator {
public static void main(String[] args) {
int a = 12;
int b = 18;
int lcm = (a * b) / gcd(a, b);
System.out.println("LCM of " + a + " and " + b + " is: " + lcm);
}
// Method to calculate the greatest common divisor (GCD)
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
Метод 2: использование цикла while
Этот метод включает в себя поиск LCM путем увеличения переменной до тех пор, пока LCM не будет найден.
public class LCMCalculator {
public static void main(String[] args) {
int a = 12;
int b = 18;
int lcm = findLCM(a, b);
System.out.println("LCM of " + a + " and " + b + " is: " + lcm);
}
// Method to find the LCM using a while loop
public static int findLCM(int a, int b) {
int lcm = (a > b) ? a : b;
while (true) {
if (lcm % a == 0 && lcm % b == 0) {
return lcm;
}
lcm++;
}
}
}
Метод 3: использование свойства LCM
В этом методе используется свойство, согласно которому LCM(a, b) = (a * b) / НОД(a, b).
public class LCMCalculator {
public static void main(String[] args) {
int a = 12;
int b = 18;
int lcm = findLCM(a, b);
System.out.println("LCM of " + a + " and " + b + " is: " + lcm);
}
// Method to find the LCM using the LCM property
public static int findLCM(int a, int b) {
int gcd = gcd(a, b);
return (a * b) / gcd;
}
// Method to calculate the greatest common divisor (GCD)
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}