新手代碼之循環語句的簡單運用(求最小公倍數與與求最大公約數)

//求兩個數的最小公倍數
import java.util.Scanner;

public class Study3 {
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);
	System.out.print("Enter first integer: ");
	int n1 = input.nextInt();
	System.out.print("Enter second integer: ");
	int n2 = input.nextInt();
	
	int gcd = 1;
	int k = 2;

		if ((n1 < n2)){
			if (n2 % n1 == 0){
			System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + n2);
		}
			else 
				System.out.println("The smallest common multiple for " + n1 + " and " + n2 + " is " + (n1 * n2));
		}
		if ((n1 > n2)){
			if (n1 % n2 == 0){
			System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + n1);
		}
			else 
				System.out.println("The smallest common multiple for " + n1 + " and " + n2 + " is " + (n1 * n2));
		}
}}
//求兩個數的最大公約數
import java.util.Scanner;

public class Study4 {
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);
	System.out.print("Enter first integer: ");
	int n1 = input.nextInt();
	System.out.print("Enter second integer: ");
	int n2 = input.nextInt();
	
	int gcd = 1;
	int k = 2;
	while (k <= n1 && k <= n2){
		if (n1 % k == 0 && n2 % k == 0)
			gcd = k;
		k++;
	}
	System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd);
	
}}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章