Trong bài viết này, chúng ta sẽ tìm hiểu cách tìm UCLN (Ước chung lớn nhất) của hai số trong Java. UCLN của hai số là số lớn nhất chia hết cho cả hai.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào:
Giá trị 1: 18, Giá trị 2: 24
Đầu ra
Kết quả mong đợi:
UCLN của hai số: 6
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo 3 số nguyên: input_1, input_2, gcd Bước 3 - Nhập hai số từ người dùng hoặc hardcode Bước 4 - Đọc giá trị Bước 5 - Kiểm tra số chia hết cho cả hai. Nếu chia hết lưu vào biến. Bước 6 - Hiển thị giá trị UCLN Bước 7 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.
import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
int input_1, input_2, gcd;
Scanner reader = new Scanner(System.in);
System.out.println("A reader object has been defined");
System.out.print("Enter a first number: ");
input_1 = reader.nextInt();
System.out.print("Enter a second number: ");
input_2 = reader.nextInt();
gcd = 1;
for (int i = 1; i <= input_1 && i <= input_2; i++) {
if (input_1 % i == 0 && input_2 % i == 0)
gcd = i;
}
System.out.printf("\nThe GCD of %d and %d is: %d", input_1, input_2, gcd);
}
}
Đầu ra
A reader object has been defined Enter a first number: 24 Enter a second number: 18 The GCD of 24 and 18 is: 6
Ví dụ 2: Giá trị định nghĩa trước
Hai số đã được định nghĩa trước.
public class GCD {
public static void main(String[] args) {
int input_1, input_2, gcd;
input_1 = 12;
input_2 = 18;
gcd = 1;
System.out.print("The first number is " + input_1);
System.out.print("\nThe second number is " + input_2);
for (int i = 1; i <= input_1 && i <= input_2; i++) {
if (input_1 % i == 0 && input_2 % i == 0)
gcd = i;
}
System.out.printf("\nThe GCD of %d and %d is: %d", input_1, input_2, gcd);
}
}
Đầu ra
The first number is 24 The second number is 18 The GCD of 24 and 18 is: 6