Java 常见例子

HCF 代表最高公因数。两个数的 HCF 是能整除这两个数的最大数。

例如 - 20 和 25 的 HCF 是 5,50 和 100 的 HCF 是 50。

方法1:使用For循环求两个数字的HCF

在下面的例子中,for循环用于将变量i从0迭代到较小的数字。如果两个数字都能被 i 整除,则它会修改 HCF,并最终给出两个数字的 HCF。

public class MyClass {
  public static void main(String[] args) {
    int x = 50;
    int y = 100;
    int hcf = 1;
    int temp;

    if (x > y) {
      temp = x;
      x = y;
      y = temp;
    }

    for(int i = 1; i < (x+1); i++) {
      if (x%i == 0 && y%i == 0)
        hcf = i;
    }

    System.out.println("HCF of "+ x +" and "+ y +" is: "+ hcf);
  }
} 

上面的代码将给出以下输出:

HCF of 50 and 100 is: 50 

方法二:使用While循环求两个数的HCF

在下面的例子中,较大的数被替换为一个大数减去较小数的数数字。继续该过程,直到两个数字相等,这将是两个数字的 HCF。

public class MyClass {
  public static void main(String[] args) {
    int p, q, x, y;
    p = x = 20;
    q = y = 25;

    while (x != y) {
      if (x > y)
        x = x - y;
      else
        y = y - x;
    }

    System.out.println("HCF of "+ p +" and "+ q +" is: "+ x);
  }
} 

上面的代码将给出以下输出:

HCF of 20 and 25 is: 5 

方法3:使用递归函数求两个数的HCF

In下面的例子,使用了递归函数。在此方法中,不使用减法运算符(如上例所示),而是使用模运算符。此方法也称为欧几里得算法

public class MyClass {
  static int hcf(int x, int y) {
    if (y == 0)
      return x;
    return hcf(y, x%y);  
  }

  public static void main(String[] args) {
    int x = 250;
    int y = 475;

    System.out.println("HCF of "+ x +" and "+ y +" is: "+ hcf(x,y));
  }
} 

上面的代码将给出以下输出:

HCF of 250 and 475 is: 25