ในบทความนี้ เราจะทำความเข้าใจวิธีค้นหา GCD ของตัวเลขสองตัวใน Java ตัวหารร่วมที่ยิ่งใหญ่ที่สุด (GCD) ของตัวเลขสองตัวคือจำนวนที่มากที่สุดที่หารทั้งสองตัว
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Value_1 : 18 Value_2 : 24
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็น −
GCD of the two numbers : 6
อัลกอริทึม
Step1- Start Step 2- Declare three integers: input_1, inpur_2 and gcd Step 3- Prompt the user to enter two integer value/ Hardcode the integer Step 4- Read the values Step 5- Check that the number divides both (x and y) numbers completely or not. If divides completely store it in a variable. Step 6- Display the ‘i’ value as GCD of the two numbers Step 7- Stop
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา
.
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);
}
} ผลลัพธ์
A reader object has been defined Enter a first number: 24 Enter a second number: 18 The GCD of 24 and 18 is: 6
ตัวอย่างที่ 2
ในที่นี้ มีการกำหนดจำนวนเต็มก่อนหน้านี้ และเข้าถึงและแสดงค่าบนคอนโซล
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);
}
} ผลลัพธ์
The first number is 24 The second number is 18 The GCD of 24 and 18 is: 6