Java 程序求两个数的最大公约数(GCD)或最大公因子 (HCF)


公约数 (H.C.F / Highest Common Factor) 是两个或更多值的最大公因子。

例如,12 和 16 的因子是 −

12 → 1, 2, 3, 4, 6, 12
16 → 1, 2, 4, 8, 16

公因子为 1、2、4,最大公因子为 4。

算法

  • 定义两个变量 - A 和 B

  • 设置循环从 1 到 A 和 B 的最大值

  • 检查二者是否都能被当前循环数完全整除,如果是,则存储此数

  • 显示存储的数字为 HCF

示例:使用 Java for 循环

import java.util.Scanner; public class GCDOfTwoNumbers { public static void main(String args[]){ int a, b, i, hcf = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter first number :: "); a = sc.nextInt(); System.out.println("Enter second number :: "); b = sc.nextInt(); for(i = 1; i <= a || i <= b; i++) { if( a%i == 0 && b%i == 0 ) hcf = i; } System.out.println("HCF of given two numbers is ::"+hcf); } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

Enter first number ::
625
Enter second number ::
125
HCF of given two numbers is ::125

更新于: 14-Jun-2024

33 千 + 次浏览

启动你的 职业

完成课程获得认证

开始吧
广告