Java 程序:计算两个数的 GCD
原文:https://www.studytonight.com/java-programs/java-program-to-calculate-gcd-of-two-numbers
在本教程中,我们将学习如何在 java 中找到两个数字的最大公约数(GCD)。两个或两个以上数字的最高公因数( HCF )或最大公约数( GCD )被定义为精确划分它们的最大数字。但是在继续之前,如果你不熟悉 java 中循环的概念,那么一定要查看关于 Java 中循环的文章。
输入:输入第一个数字:3
输入第二个数字:5
输出:3 和 5 两个数的 HCF 为 1
Java 程序:程序 1:计算两个数的 GCD
在这个程序中,我们将看到如何使用 for 循环在 java 中计算两个数字的 GCD。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明两个变量。
- 要求用户初始化这些变量。
- 声明一个变量来存储 HCF,并将其初始化为 0。
- 使用 for 循环计算 GCD。
- 如果这两个数字都可以被循环变量整除,那么将这个数字设置为 GCD。
- 继续这个过程,直到找到最大的数,这个数除以两个数而没有余数。
- 打印结果。
- 停下来。
//Java Program to Calculate the GCD of two numbers
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
int num1 = sc.nextInt();
System.out.println("Enter the second number: ");
int num2 = sc.nextInt();
int hcf=0;
for(int i = 1; i <= num1 || i <= num2; i++)
{
if( num1%i == 0 && num2%i == 0 )
hcf = i;
}
System.out.println("HCF of given two numbers is :"+hcf);
}
}
输入第一个数字:2 输入第二个数字:6 给定两个数字的 HCF 为:2
Java 程序:程序 2:计算两个数的 GCD
在这个程序中,我们将看到如何使用 while 循环在 java 中计算两个数字的 GCD。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明两个变量。
- 要求用户初始化这些变量。
- 使用 while 循环计算 GCD。
- 从较大的整数中减去较小的整数,并将结果赋给持有较大整数的变量
- 继续这个过程,直到两个数字相等。
- 打印结果。
- 停下来。
//Java Program to Calculate the GCD of two numbers
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
int num1 = sc.nextInt();
System.out.println("Enter the second number: ");
int num2 = sc.nextInt();
while(num1 != num2)
{
if(num1 > num2)
{
num1 -= num2;
}
else
{
num2 -= num1;
}
}
System.out.println("HCF of given two numbers is :"+num1);
}
}
输入第一个数字:2 输入第二个数字:7 给定两个数字的 HCF 为:1
Java 程序:程序 3:计算两个数的 GCD
在这个程序中,我们将看到当数字为正数或负数时,如何使用 while 循环来计算 java 中两个数字的 GCD。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明两个变量。
- 要求用户初始化这些变量。
- 首先将两个数字都设置为正数。
- 使用 while 循环计算 GCD。
- 从较大的整数中减去较小的整数,并将结果赋给持有较大整数的变量
- 继续这个过程,直到两个数字相等。
- 打印结果。
- 停下来。
//Java Program to Calculate the GCD of two numbers
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
int num1 = sc.nextInt();
System.out.println("Enter the second number: ");
int num2 = sc.nextInt();
num1 = ( num1 > 0) ? num1 : -num1;
num2 = ( num2 > 0) ? num2 : -num2;
while(num1 != num2)
{
if(num1 > num2)
{
num1 -= num2;
}
else
{
num2 -= num1;
}
}
System.out.println("HCF of given two numbers is :"+num1);
}
}
输入第一个数字:-12 输入第二个数字:6 给定两个数字的 HCF 为:6