//根据老师的要求,用这种算法求最小公倍数。总是有错
import javax.swing.JOptionPane;
public class LCM {
/** Main methed */
public static void main(String[] args) {
// Prompt user input the two numbers
String oneString = JOptionPane.showInputDialog(null,
"Please input the first number:", "Input",
JOptionPane.INFORMATION_MESSAGE);
String twoString = JOptionPane.showInputDialog(null,
"Please input the second number:", "Input",
JOptionPane.INFORMATION_MESSAGE);
// Convert the two strings into int value
double oneDouble = Double.parseDouble(oneString);
double twoDouble = Double.parseDouble(twoString);
double twoNumbersLcm; // 定义的这个字段用来存放最后的结果,也就是两个数的最小公倍数
twoNumbersLcm = lcm(oneDouble, twoDouble);
JOptionPane.showMessageDialog(null, "The lease common multiple is "
+ twoNumbersLcm, "Answer", JOptionPane.INFORMATION_MESSAGE);
}
// 求最小公倍数
public static double lcm(double one, double two) {
double[][] ones = new double[10][2];
double[][] twos = new double[10][2];
double commonMultiple = 1;
divide(ones, one);
divide(twos, two);
commonMultiple = multiple(ones, twos);
return commonMultiple;
}
// 求因子,并将得到的因子和出现的次数存到二维数组中
public static void divide(double array[][], double dividend) {
int i = 0;
double divisor = 2.0;
do {
while (dividend % divisor == 0) {
array[i][0] = divisor;
array[i][1]++;
dividend = dividend / divisor;
}
i++;
divisor++;
} while (dividend != 1);
}
//
public static double multiple(double arrayOne[][], double arrayTwo[][]) {
int i = 0;
double power = 1;
// 去次数较大的因子相乘,得到最小公倍数
while (i<=arrayOne.length || i<=arrayTwo.length) {
if (arrayOne[i][0] == arrayTwo[i][0]) {
if (arrayOne[i][1] >= arrayTwo[i][1])
power *= Math.pow(arrayOne[i][0], arrayOne[i][1]);
else
power *= Math.pow(arrayTwo[i][0], arrayTwo[i][1]);
} else
power = Math.pow(arrayOne[i][0], arrayOne[i][1])
* Math.pow(arrayTwo[i][0], arrayTwo[i][1]);
i++;
}
if (arrayOne[i][0] != 0)
power *= Math.pow(arrayOne[i][0], arrayOne[i][1]);
else
power *= Math.pow(arrayTwo[i][0], arrayTwo[i][1]);
return power;
}
}