Java程序查找两个数的LCM

编写一个Java程序,使用While循环和递归方法查找两个数的LCM。根据数学,两个或多个整数的LCM(最小公倍数)是可被分配的整数值(无余数)整除的最小正整数。

例如,2和3的LCM是6,因为6是可被2和3整除的最小正整数。

Java程序使用While循环查找两个数的LCM

此Java程序允许用户输入两个正整数。接下来,在此程序中,我们使用While循环和临时变量来计算这两个正整数的LCM。

import java.util.Scanner;
public class Example {
	private static Scanner sc;
	public static void main(String[] args) {
		int n1, n2, Temp, GCD = 0, LM = 0;
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter the First Integer Value : ");
		n1 = sc.nextInt();	
		
		System.out.print("Please Enter the Second Integer Value : ");
		n2 = sc.nextInt();
		
		int a = n1;
		int b = n2;
		
		while(n2 != 0)
	    {
			Temp = n2;
			n2 = n1 % n2;
			n1 = Temp;
	    }
		GCD = n1;
		System.out.println("\nGCD of " + a + " and " + b + "  =  " + GCD);
		
		LM = (a * b) / GCD;
		System.out.println("LCM of " + a + " and " + b + "  =  " + LM);
		
	}
}
Program to find LCM of Two Numbers using While Loop

分析

n1 = 2 和 n2 = 3

while循环将一直迭代,直到其中的条件,即n2 != 0,为假。所以,让我向您展示迭代式的代码执行。

第一次迭代:n2 != 0 意味着 3 != 0 为真。

  • temp = 3
  • n2 = 2 % 3 = 1
  • n1 = temp = 3

第二次迭代:1 != 0 为真。

  • temp = 1
  • n2 = 3 % 1 = 0
  • n1 = 1

条件 while (n2 != 0) 变为 False。因此,Javac退出while循环。

GCD = n1 = 1

LCM = (2 * 3) / 1 = 6。

如何在不使用Temp的情况下查找两个数的LCM?

此程序在不使用任何临时变量的情况下计算最小公倍数。

import java.util.Scanner;

public class LCMofTwo2 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int Num1, Num2, GCD = 0, LCM = 0;
		sc = new Scanner(System.in);
	
		System.out.print(" Please Enter the First Integer Value : ");
		Num1 = sc.nextInt();	
	
		System.out.print(" Please Enter the Second Integer Value : ");
		Num2 = sc.nextInt();
	
		int a = Num1;
		int b = Num2;
	
		while(Num2 != 0)
	    {
			if(Num1 > Num2)
			{
				Num1 = Num1 - Num2;
			}
			else
			{
				Num2 = Num2 - Num1;
			}
	    }
		GCD = Num1;
		System.out.println("\n GCD of " + a + " and " + b + "  =  " + GCD);
	
		LCM = (a * b) / GCD;
		System.out.println("\n LCM of " + a + " and " + b + "  =  " + LCM);
	}
}

Java程序使用递归函数查找两个数的LCM

此程序通过递归调用HCFofTwo函数来计算最大公约数。接下来,此程序从GCD中找到最小公倍数。

import java.util.Scanner;
public class Example {
	private static Scanner sc;
	public static void main(String[] args) {
		int n1, n2, GCD = 0, LM = 0;
		sc = new Scanner(System.in);

		System.out.print("Please Enter the First Integer Value : ");
		n1 = sc.nextInt();	

		System.out.print("Please Enter the Second Integer Value : ");
		n2 = sc.nextInt();

		GCD = HCFofTwo(n1, n2);		
		System.out.println("\nGCD of " + n1 + " and " + n2 + "  =  " + GCD);

		LM = (n1 * n2) / GCD;
		System.out.println("LCM of " + n1 + " and " + n2 + "  =  " + LM);
	}
	public static int HCFofTwo(int n1, int n2)
	{
		if(n2 == 0)
		{
			return n1;
		}
		else
		{
			return HCFofTwo(n2, n1 % n2);
		}
	}
}
program to find LCM of Two Numbers using Recursion