下面的方法是用递归解决的。如求几个整数的最小公倍数的时候,先求前两个的最小公倍数,然后求这个数与第三个数的最小公倍数,依次,即可求出。
public class LeastCommonMultiple
{
public static void main(String[] args)
{
int[] arr = {6, 9, 3, 12};
int result = -1;
LeastCommonMultiple lcm = new LeastCommonMultiple();
result = lcm.getMinCommonMultiple(arr);
System.out.println(result);
result = lcm.getMaxDivisor(arr);
System.out.println(result);
}
public int getMinCommonMultiple(int[] arr)
{
int result = arr[0];
for(int i=1; i<arr.length; i++)
{
result = getMinCommonMultiple(result, arr[i]);
}
return result;
}
public int getMaxDivisor(int[] arr)
{
int result = arr[0];
for(int i=1; i<arr.length; i++)
{
result = getMaxDivisor(result, arr[i]);
}
return result;
}
public int getMinCommonMultiple(int a, int b)
{
int result = -1;
int temp = -1;
temp = getMaxDivisor(a, b);
result = a * b;
result = result / temp;
return result;
}
public int getMaxDivisor(int a, int b)
{
int temp = -1;
if(a < b)
{
temp = a;
a = b;
b = temp;
}
while(b != 0)
{
a = a % b;
temp = a;
a = b;
b = temp;
}
return a;
}
}
输出为:
36
3