HCF或最高公因子是两个或多个值的最大公因数。
例如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
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); } }
输出结果
Enter first number :: 625 Enter second number :: 125 HCF of given two numbers is ::125