Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để tìm GCD của hai số

Trong bài này, chúng ta sẽ hiểu cách tìm GCD của hai số trong Java. Số chia chung lớn nhất (GCD) của hai số là số lớn nhất mà chia cả hai số đó.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

Value_1 : 18
Value_2 : 24

Đầu ra

Đầu ra mong muốn sẽ là -

GCD of the two numbers : 6

Thuật toán

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

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để tìm GCD của hai số .

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

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.

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